0

So I'm attempting to run a generator from within a controller the idea being that i could generate a scaffold from within a rails application

for testing purposes ive created a small generator that creates an initializer with no real content. i've run this from within the shell (rails generate initializer)

lib/generators/initializer_generator.rb
    class InitializerGenerator < Rails::Generators::Base
      def create_initializer_file
        create_file "config/initializers/initializer.rb", "# Add initialization content here"
      end
    end

but the problem comes in when i attempt to run the generator from a controller

class GeneratorController < ApplicationController
  include Rails::Generators
  include Rails::Generators::Actions

  def index
    generate(:initializer)
  end

end

so this bring the response 'undefined method `behavior' then i did some research knowing that rails generators are based apon Thor and found that the behavior method is a thor method in the Thor::Actions modules http://rubydoc.info/github/wycats/thor/master/Thor/Actions:behavior

So I changed the controller code to include that module:

class GeneratorController < ApplicationController
    include Rails::Generators
    include Rails::Generators::Actions
    include Thor::Actions

  def index
    generate(:initializer)
  end

end

Now the error is 'wrong number of arguments (3 for 0)'. Am very confused now about what might be going wrong.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Ben
  • 21
  • 3

1 Answers1

0

Have you tried calling the class directly?

InitializerGenerator.new.initializer

This is an advantage of Thor over Rake, these are regular Ruby classes.

I had to set the destination_root inside my method, example:

  def create_initializer_file
    destination_root = Rails.root
    create_file "config/initializers/initializer.rb", "# Add initialization content here"
  end

I've only just started using generators so there might be a better way.

One issue I ran in to after this, which I have yet to solve is that Thor prompts for user input if the file already exists.

Kris
  • 19,188
  • 9
  • 91
  • 111