Skip to content

Instantly share code, notes, and snippets.

@olbat
Last active May 5, 2017 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olbat/5ae63d31fc9c0fdcd475aaef0d025124 to your computer and use it in GitHub Desktop.
Save olbat/5ae63d31fc9c0fdcd475aaef0d025124 to your computer and use it in GitHub Desktop.
Ruby script that rewrite source code collapsing nested modules definitions
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