Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend a class from an initializer and have it reload in development environment?

I am extending a class (which is in a plugin) by including a module, this is done in an initializer.

require 'qwerty/core/user'
User.send :include, Qwerty::Core::Extensions::User

However in development before every request (and after reload! is called in the console) all models are reloaded but because the initializers are not run again the module is not included. Leaving a model with 'missing parts'.

Because the model is in a plugin it does not seem wise to include code directly in the class which would be the usual approach.

For now I have simply added a before_filter which includes the module if in development environment. But I have copy/pasted and have duplicate code in the initializer and application controller.

  # Class extensions in initalizers are over-writtern each request
  def development_loading
    if RAILS_ENV == 'development'      
      User.send :include, Qwerty::Core::Extensions::User
    end
  end

Is there a better way?

As a side note the plugin is mine, so I could add code in to it, but the extensions held in the module may not always be present...

like image 945
Kris Avatar asked Oct 07 '09 12:10

Kris


1 Answers

environment.rb

config.to_prepare do
  User.send :include, Qwerty::Core::Extensions::User
end

The code is the block is run before every request in development mode and once in production mode.

like image 61
Kris Avatar answered Oct 04 '22 20:10

Kris