Skip to content

Instantly share code, notes, and snippets.

@paneq
Created September 13, 2018 12:42
Show Gist options
  • Save paneq/615b6e26e2f4acd6f4d163875a4fa6c7 to your computer and use it in GitHub Desktop.
Save paneq/615b6e26e2f4acd6f4d163875a4fa6c7 to your computer and use it in GitHub Desktop.
Rewrite constant to a method
require 'pry'
require 'parser'
require 'parser/current'
class ConstToMethodRewriter < ::Parser::Rewriter
def on_casgn(node)
_, const_name, *args = node.children
replace_range = node.location.expression
const_value = args.first.location.expression.source
case const_name
when :LABEL
replace(replace_range, "def self.label\n #{const_value}\n end")
end
end
end
Dir.glob("app/models/package/*.rb").each do |filename|
source = File.read(filename)
parser = Parser::CurrentRuby.new
rewriter = ConstToMethodRewriter.new
buffer = Parser::Source::Buffer.new(filename)
buffer.source = source
new = rewriter.rewrite(buffer, parser.parse(buffer))
File.open(filename, "w"){|f| f.write(new) }
end
@paneq
Copy link
Author

paneq commented Sep 13, 2018

Effect:

-  LABEL = 'Something (xlsx)'
+  def self.label
+    'Something (xlsx)'
+  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment