Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Ruby script that rewrite source code collapsing nested modules definitions
src =
# 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)
puts src
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.