Created
September 13, 2018 12:42
-
-
Save paneq/615b6e26e2f4acd6f4d163875a4fa6c7 to your computer and use it in GitHub Desktop.
Rewrite constant to a method
This file contains 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Effect: