Domanda

I tying to create a generator to create some custom scaffolding for a system I am working on in Rails 4. I have a basic generator with this line that copies a file from the template to the destination.

 copy_file "controllers/module_controller.rb", "app/controllers/#{file_name}_controller.rb"

This works fine but what I am wondering is how to use #{file_name} from within the template? For example can I do something like this?

 class <%= "#{file_name}" %>Controller < ApplicationController
È stato utile?

Soluzione 2

I guess you use erb for custom scaffolding. create generic_controller.erb

class <%= controller_name %>Controller < ApplicationController
    some stuff using erb
end

Then you can evaluate it like

controller_name = 'Something'
ERB.new(File.read('generic_controller.erb')).run(binding())

this will give you

class SomethingController < ApplicationController
    some stuff using erb
end

hope this will help you

Altri suggerimenti

Although I did it a little differently. We will need to use the template method instead of copy_file.

class SomethingGenerator < Rails::Generators::NamedBase
  source_root File.expand_path('../templates', __FILE__)
  def copy_files
    # Controller
    template "controllers/something_controller.erb", "app/controllers/#{something_name}_controller.rb"
  end

  private
  def something_name
    file_name.underscore
  end
end

This works for views and other files as well. The key is to use .erb files as pointed out by Dileep Nandanam.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top