如何从初始化程序扩展一个类并让它在开发环境中重新加载? [英] How to extend a class from an initializer and have it reload in development environment?

查看:33
本文介绍了如何从初始化程序扩展一个类并让它在开发环境中重新加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过包含一个模块来扩展一个类(它在插件中),这是在初始化程序中完成的.

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

但是在开发中,在每次请求之前(以及在控制台中调用 reload!之后)所有模型都被重新加载,但是因为初始化程序不会再次运行,所以模块不包括在内.留下带有缺失部件"的模型.

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.

现在我只是简单地添加了一个 before_filter ,它包含开发环境中的模块.但是我复制/粘贴并且在初始化程序和应用程序控制器中有重复代码.

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

有没有更好的方法?

顺便说一句,插件是我的,所以我可以向其中添加代码,但模块中保存的扩展可能并不总是存在...

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...

推荐答案

environment.rb

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.

这篇关于如何从初始化程序扩展一个类并让它在开发环境中重新加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆