Skip to content

Instantly share code, notes, and snippets.

@bluerabbit
Created August 25, 2020 01:08
Show Gist options
  • Select an option

  • Save bluerabbit/cadf6f0242fda3f18f2f7e047cde44b4 to your computer and use it in GitHub Desktop.

Select an option

Save bluerabbit/cadf6f0242fda3f18f2f7e047cde44b4 to your computer and use it in GitHub Desktop.

Revisions

  1. bluerabbit created this gist Aug 25, 2020.
    33 changes: 33 additions & 0 deletions method_rewriter.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    # 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