Skip to content

Instantly share code, notes, and snippets.

@mbulat
Last active December 26, 2015 21:28
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 mbulat/7215869 to your computer and use it in GitHub Desktop.
Save mbulat/7215869 to your computer and use it in GitHub Desktop.
Ruby script to generate generator commands from existing models
# RUN THIS FROM WITHIN THE RAILS CONSOLE OF THE APP
# WITH THE MODELS YOU'RE USING AS A TEMPLATE
RAILS_COMMAND = "rails g resource"
RAILS_COMMAND_OPTIONS = "--skip-migration"
FILE_NAME = "resource_generation.rb"
# First, ensure we've loaded all of the model classes
Dir.glob("#{Rails.root}/app/models/*.rb").sort.each { |file| require_dependency file }
models = []
commands_to_run = []
Module.constants.select do |constant_name|
constant = eval constant_name.to_s
if not constant.nil? and constant.is_a? Class and constant.superclass == ActiveRecord::Base
models << constant_name.to_s
end
end
models.each do |model|
attributes_string = (eval model).columns_hash.map {|h| "#{h[0]}:#{h[1].type}" }.join(" ")
command_string = "system('#{RAILS_COMMAND} #{model} #{attributes_string} #{RAILS_COMMAND_OPTIONS}')"
commands_to_run << command_string
end
File.open(FILE_NAME, 'w') do |file|
file.puts "#!/usr/bin/env ruby"
commands_to_run.each do |command_to_run|
file.puts command_to_run
end
file.chmod(0755)
end
@mbulat
Copy link
Author

mbulat commented Oct 29, 2013

Then simply move the command to your new Rails app and run

./resource_generation.rb

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