Last active
May 5, 2017 11:50
-
-
Save olbat/5ae63d31fc9c0fdcd475aaef0d025124 to your computer and use it in GitHub Desktop.
Ruby script that rewrite source code collapsing nested modules definitions
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
src = STDIN.read | |
# iterate on "1st level" module definitions | |
src.dup.scan(/^module [^;]+$.+?^end/m) do |mod| | |
# get the nested modules' definitions | |
mdefs = mod.scan(/^ *module [^\n]+$(?=\n +module)/m).map(&:to_s) | |
# stop if there is no nested module definition | |
next if mdefs.empty? | |
ndefs = mdefs.size | |
# get the last definition that's not extracted because of the look ahead | |
mdefs << mod.match(/\A(?:^ *module [^\n]+\n)+(^ +module [^\n]+)/m)[1].to_s | |
# collapse nested modules' definitions | |
mdefs = mdefs.join("\n") | |
newmod = mod.gsub(/\A#{mdefs}/m, mdefs.gsub(/\n^ +module /m, '::')) | |
# removes useless closure of modules' blocks | |
newmod.gsub!(/(^ +end\n){#{ndefs}}end\Z/m, 'end') | |
# re-indent the code contained in the module | |
newmod.gsub!(/^ {#{ndefs * 2}}/, '') | |
# replace the module's definition in the source code | |
src.sub!(mod, newmod) | |
end | |
puts src |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment