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?
At the point
some_custom_methodis called, attributes are already set (viaARGV) and by checking the code I don’t see a clear way to alter them from there. You can use another approach by overridingstartclass method in your generator and manipulate the args directly, like this: