Generators in Rails 2.3
The other day I started looking in to how to create generators in Rails 2.3. I came across a couple of articles on the topic that provided a good starting point, still was a bit confused about a couple things.
I couldn’t figure out exactly how to get information to templates at first. The solution: simply add an attr_reader
corresponding to the instance variable in initialize()
. In this case, hello.
class FoosGenerator < Rails::Generators::Base
attr_reader :hello
attr_accessor :attributes
def initialize(runtime_args, runtime_options = {})
super
@hello = runtime_args.first
@attributes = []
end
def manifest
m.template foo.erb
end
end
and in templates/foo.erb, just put an erb tag with a local variable name.
<%= foo %>
At this point, you might be wondering, like I did, “What about erb files? How do you differentiate between erb to interpret now in the generation process and that for later when a template is rendered, say?”
<%% for later %>
<%%= also for later %>
<%%= <%= for now %> %>
<% for now %>
Note that the double % occurs only in the opening erb tag.
When I discovered that the first link above contained a link to the code for rails 2.3 generators and dug around a bit in there, most of this became clear pretty quickly.
Something that took a bit more effort to suss out was how to accept runtime options that had a string value instead of boolean.
class FoosGenerator < Rails::Generators::Base
...
protected
def add_options!(opt)
opt.separator ''
opt.separator 'Options:'
opt.on("--boolean-option", "Set boolean option to true") { |v| options[:boolean_option] = v }
opt.on("-d", "--description=name", String, "Specify a description", "Default: mysql") { |v| options[:description] = v }
end
end
Note that the “Default: mysql” bit is just part of the help output. You’d have to write logic to actually make this function as promised.