views:

165

answers:

2

I'm writing a generator that adds a few files that my server will use. I'd also like to add a line to the environment.rb file. Can this be done with a generator or should I be using an app template?

+2  A: 

Rather than modifying environment.rb, check out what you can do with Rails initializers. Basically, you're just going to create a new Ruby .rb file within config/initializers and keep your configuration loading code in there. If you need per-environment configuration, it's best to create another (usually YAML) file within config/ that will store the per-environment configuration variables and load that YAML in your initializer.

m104
Thanks. That will work even better than what I had in mind.
Jarrod
+2  A: 

You can use initializers for custom initialization code, but if you find adding to an existing file with a generator is appropriate here's how the built-in generators do it:

# Excerpted from template_runner.rb

# Make an entry in Rails routing file conifg/routes.rb 
def route(routing_code)
  log 'route', routing_code
  sentinel = 'ActionController::Routing::Routes.draw do |map|'

  in_root do
    gsub_file 'config/routes.rb', /(#{Regexp.escape(sentinel)})/mi do |match|
      "#{match}\n  #{routing_code}\n"
    end
  end
end

As you can see, it's just figuring out where they want the code to go (the sentinal line) and stuffing the new line in right after it.

Baldu