Question

I'm trying to make simple view generator and using DRY principle, I don't want to have my own html (erb/haml/slim) templates. I'd like my generator to hook to existing template engine and pass it some arguments.

My view_generator.rb file looks like this:

class ViewGenerator < Rails::Generators::NamedBase
  source_root File.expand_path('../templates', __FILE__)
  argument :attributes, :type => :array, :default => [], :banner => "field:type field:type"

def some_custom_method
  (...)
end

hook_for :template_engine, :as => :scaffold

end

Everything works fine like this. What I'd like to do in my some_custom_method is to add couple of attributes:

def some_custom_method
  new_attribute = Rails::Generators::GeneratedAttribute.new("description")
  new_attribute.type = :integer
  attributes << new_attribute
end

What happens is that I insert new_attribute in attributes array, but when the hook_for is executed, the attribute variable reverts back to original one passed from command line.

How can I bypass this?

Was it helpful?

Solution

At the point some_custom_method is called, attributes are already set (via ARGV) and by checking the code I don't see a clear way to alter them from there. You can use another approach by overriding start class method in your generator and manipulate the args directly, like this:

class ViewGenerator < Rails::Generators::NamedBase
  # your code ...
  def self.start(args, config)
    args.insert(1, 'description:integer') # 0 being the view name
    super
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top