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

前端 未结 5 1916
感动是毒
感动是毒 2021-02-08 00:03

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::Co         


        
相关标签:
5条回答
  • 2021-02-08 00:24

    Why do you use initializers to include functionality?

    Try the following instead:

    require 'qwerty/core/user'
    class User < ActiveRecord::Base
      include Qwerty::Core::Extensions::User
      # bla bla
    end
    
    0 讨论(0)
  • 2021-02-08 00:31

    At first I was going to advise something about adding a 'development' directory to the front of your load path in development mode, so that your revisions would always get reloaded first... But then it occurred to me that you said something confusing.

    The model you're trying to extend. It's in a plugin? Plugins aren't supposed to be reloaded by default in development mode, unless the app explicitly says they should in its configuration by setting Config.reload_plugins? to false.

    But if, for some reason, your plugin is reloading anyway and you don't want it to, you can put this in your plugin's init.rb to explicitly say it shouldn't reload:

    Dependencies.load_once_paths << lib_path
    

    See the Rails docs on the Configuration class for more detail: http://api.rubyonrails.org/classes/Rails/Configuration.html#M002536

    0 讨论(0)
  • 2021-02-08 00:45

    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.

    0 讨论(0)
  • 2021-02-08 00:49

    In Rails 3.x you can configure a block to run every time reloads happen (in development mode, or when config.cache_classes = false). This would go in an initializer:

    ActionDispatch::Callbacks.to_prepare do
        # configure stuff or initialize
    end
    
    0 讨论(0)
  • 2021-02-08 00:50

    Slightly more elegant solution than the one accepted since it can be put in an initializer:

    require 'dispatcher'
    
    Dispatcher.to_prepare do
      # stuff that needs to happen once per initialization
    end
    
    0 讨论(0)
提交回复
热议问题