Search code examples
ruby-on-railsgeneratorthor

How to change source for a custom rails generator? (Thor)


I'm making a custom generator that generates a new rails app, and I do it like this

require 'thor'
require 'rails/generators/rails/app/app_generator'

class AppBuilder < Rails::AppBuilder
  include Thor::Actions
  include Thor::Shell
  ...
end

The problem is, how do I add a new source directory (which is then used by Thor::Actions#copy_file, Thor::Actions#template, and the others)? I saw in the Thor's documentation that Thor::Actions#source_paths holds the sources (it's an array of paths), so I tried overriding it inside my class (since I've included Thor::Actions):

def source_paths
  [File.join(File.expand_path(File.dirname(__FILE__)), "templates")] + super
end

With this I wanted to add the ./templates directory in the sources, while still keeping the Rails' one (that's why the + super at the end). But it doesn't work, it still lists the Rails' source path as the only one.

I tried browsing through the Rails' source code, but I couldn't find how Rails put his directory in the source paths. And I really want to know that :)


Solution

  • This worked:

    require 'thor'
    require 'rails/generators/rails/app/app_generator'
    
    module Thor::Actions
      def source_paths
        [MY_TEMPLATES]
      end
    end
    
    class AppBuilder < Rails::AppBuilder
      ...
    end
    

    I don't understand why, but I've spent too much time on this already, so I don't care.