views:

19

answers:

1

Hi,

I would like to know where put monkey patching code like the following in my rails application which would open up existing classes and add or override new functionality. I want this code to be available to all instances as soon as possible. Is autoload the correct way of doing this and putting the call in environment.rb?

class Class
  def attr_initializer(*attributes)
    attr_reader *attributes
    class_eval <<-RUBY
      def initialize(#{attributes.join(', ')})
        #{attributes.map{ |attribute| "@#{attribute}" }.join(', ')} = #{attributes.join(', ')}
      end
    RUBY
  end
end
+2  A: 

If you are using rails 2.3.x then the standard place to put these is within a file in the config/initializers directory. Rails will load these files early in the boot process.

Steve Weet
Thanks, how about when running tests, do I need to add any code in the test_helper to initialize this code also?
dagda1
These initializers will be run when the test suite loads. The files in config/initialiers is run for all environments
Steve Weet