Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-plugins

Rails Generator: generate files based on already existing rails files


I wanted to make a generator that created files (and directories, etc...) based on already existing files in the app (for instance, the views or controllers). So if we had views set up like this

-app
   -views 
        - layouts
             - application.html.erb
        - users
             - index.html.erb
             - show.html.erb 
             - etc ...

and I wanted to create files based on them I can do (with just ruby)

directories = Dir.entries("#{Rails.root}/app/views")
directories.each do |directory|
  unless directory == "." or directory == ".."
    files = Dir.entries("#{Rails.root}/app/views/#{directory}")
    files.each do |file|
      unless file == "." or file == ".."
        text = File.read("#{Rails.root}/app/views/#{directory}/#{file}")      
        something #=> whatever else needs to go here to edit the file
        something else #=> output_file.puts whatever
      end
    end
  end
end

so this is basically what I would like to do with a generator so I can roll my code into a plugin and use it for other apps.

First question, how can I generate arbitrary files (with filenames based on existing filenames using the generator. Is it appropriate to cycle through the directories like I did above, grab the directory/file and generate files? Is there a way to do what I did using a simpler method (mine seems easily breakable).

Also, should I put all that read/format/write code inside the generator itself and just pass a string into the "initialize content" section of create_file or should I put it somewhere else. Or should I use the generator to create the bare files and populate it with an init script?

Is there a more rails type of way of populating generated files, or should I just shove all my formatting code inside the generator. If so, what is the appropriate way to approach this.


Solution

  • I am not sure if you want to know how generators are built in rails3 or not. The code you are showing is not very generator-like. In generators you can use all commands from Thor, which offers you a very powerful toolset of manipulating files, and injecting code (strings) into classes or files.

    So I would most definitely fill your files inside a generator, because then it happens on user request, and the user can choose whether or not certain files need or can be overwritten or not.

    Inside your gem, you will have a lib/generators folder, containing a templates folder, containing all files you might want to place inside the rails application.

    From the Thor documentation, here is a nice example to construct files in a generator.

    Hope this helps.