Created
August 25, 2020 01:08
-
-
Save bluerabbit/cadf6f0242fda3f18f2f7e047cde44b4 to your computer and use it in GitHub Desktop.
Parser::TreeRewriterでrubyファイルの書き換え
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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