Skip to content

Instantly share code, notes, and snippets.

@bluerabbit
Created August 25, 2020 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluerabbit/cadf6f0242fda3f18f2f7e047cde44b4 to your computer and use it in GitHub Desktop.
Save bluerabbit/cadf6f0242fda3f18f2f7e047cde44b4 to your computer and use it in GitHub Desktop.
Parser::TreeRewriterでrubyファイルの書き換え
# gem 'parser'
# bundle exec ruby-rewrite -l method_rewriter.rb -m app.rb
class MethodRewriter < Parser::TreeRewriter
def on_def(node)
padding = ' ' * (node.location.column + 2)
insert_start(node: node, args: node.children[1].location.expression, code: node.children[2], padding: padding)
insert_after(node.children.last.location.expression, "\n#{padding}#{puts_end}")
super
end
private
def insert_start(node:, args:, code:, padding:)
return unless code
method_name = node.children.first.to_s
insert_after end_definition(node, args), "\n#{padding}#{puts_start(method_name)}"
end
def end_definition(node, args)
args || node.location.name
end
def puts_start(method_name)
"# $action_counter.audit('helper:#{method_name}') do"
end
def puts_end
'# end # action counter'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment