在Rails中扩展红宝石宝石 [英] Extending a ruby gem in Rails

查看:102
本文介绍了在Rails中扩展红宝石宝石的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如果我现在需要添加一些自定义功能,例如, (例如,添加一个属性给用户)这样做的最佳做法是什么?如果我定制了宝石,那么我将来会在更新宝石时遇到问题。



这里最好的方法是什么?

解决方案

这个问题很古老,但我觉得它可以多用一点。确实,你可以在运行时monkeypatch rails(和ruby)。这意味着很容易重新打开类或模块并注入新代码。然而,由于所有的动态类加载和卸载都是在开发模式下进行的,所以这在rails中有点棘手。



我不会详细讨论,但是您真的想要将你的扩展插入到初始化程序或gem中,因为它们在dev模式下的请求之间重新加载。如果你把代码插入到插件中,它将不会被重新加载,你会得到非常神秘的错误,比如XXX的副本已经从模块树中移除,但仍然是活动的!。



最简单的做法是将代码放入初始化程序(例如config / initializers / user_extensions.rb)。您可以使用class_eval注入代码。

  User.class_eval do 
...新代码...
end

ruby​​的可扩展性的一个主要缺点是追踪代码来自哪里。您可能希望添加有关正在加载的扩展的某种日志消息,以便人们可以追踪它。

  Rails.logger .info\\\
~~~从#{__FILE__}加载用户模型扩展名\ n
User.class_eval do
...新代码...
结束

延伸阅读:

http://airbladesoftware.com/notes/monkey-patching-a-gem-in-rails- 2-3


Let's say I have a Rails app that gets most of it's functionality from a gem (for instance, a CMS).

If I now need to add some customisation (for instance, add a property to a user) what is the best practice way of doing this? If I customise the gem, then I will have issues with updating the gem in the future.

What is the best approach to take here?

解决方案

This question is quite old, but I feel it could use a bit more fleshing out. It is true that you can monkeypatch rails (and ruby) at run-time. That means it's easy to reopen a class or module and inject new code. However, this is somewhat trickier in rails due to all the dynamic class loading and unloading that goes on development mode.

I won't go into details, but you really want to put your extensions into an initializer, or a gem, since they get reloaded between requests in dev mode. If you put the code into a plugin it won't get reloaded and you'll get very mysterious errors such as "A copy of XXX has been removed from the module tree but is still active!"

The easiest thing to do is throw the code into an initializer (e.g. config/initializers/user_extensions.rb). You can just use class_eval to inject the code.

User.class_eval do
  ... new code ...
end

One major drawback of ruby's extensibility is tracking down where code is coming from. You might want to add some kind of log message about the extensions being loaded, so people can track it down.

Rails.logger.info "\n~~~ Loading extensions to the User model from #{ __FILE__ }\n"
User.class_eval do
  ... new code ...
end

Further reading:

http://airbladesoftware.com/notes/monkey-patching-a-gem-in-rails-2-3

这篇关于在Rails中扩展红宝石宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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