如何在不编辑宝石来源的情况下将方法添加到红宝石宝石? [英] How do I add a method to a ruby gem without editing the gem source?

查看:55
本文介绍了如何在不编辑宝石来源的情况下将方法添加到红宝石宝石?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用acts_as_taggable_on gem,并且想向其中一个gem源文件(tag.rb)添加方法,但是我不想以任何方式更改gem源.

我尝试在/app/models目录或/lib目录中创建自己的tag.rb文件,然后向该文件添加所需的方法,希望ruby合并两个tag.rb文件

但是我得到一个NoMethodError: undefined method ...

我想念什么?

解决方案

我认为重新打开Tag类是正确的做法.除非它对您的代码真正有意义,否则我不会介绍其他级别的继承.

我不确定,为什么要重新打开Tag类不起作用.一些想法:

1-当您编写自己的Tag类时,它是否来自ActiveRecord :: Base? Tag类中的Tag类的作用与之类似,我可以看到忽略它可能使事情变得混乱.

2-如果我需要放置重新打开单个方法的插件类的代码的地方,则可能会将其放在初始化文件中(例如config/initializers/tag_patch.rb).只是为了保持清洁.

3-如果其他所有方法均失败,并且您仍然无法正确打开Tag类(无论出于何种原因),则可以尝试使用其他元编程技术来添加该方法.例如:

Tag.send(:define_method, method_name) do 
  #code for your method
end

I am using the acts_as_taggable_on gem and would like to add a method to one of the gem source files (tag.rb), but I do not want to change the gem source in any way.

I have tried creating my own tag.rb file to in the /app/models directory or in the /lib directory, and then adding the desired method to that file expecting that ruby will merge the two tag.rb files

But when I do I get a NoMethodError: undefined method ...

What am I missing?

解决方案

I think you're right that reopening the Tag class is the way to go. I wouldn't introduce another level of inheritance unless it really made sense for your code.

I'm not sure, off the top of my head, why reopening the Tag class didn't work. A few thoughts:

1 - When you wrote your own Tag class, did it descend from ActiveRecord::Base? The Tag class in acts as taggable on does, and I could see how neglecting that might mess things up.

2 - If I needed a place to put code that reopened a plugin class for a single method, I'd probably put it in an initializer file (such as config/initializers/tag_patch.rb). Just to keep things clean.

3 - If all else fails and you still can't get the Tag class reopened properly (for whatever reason) there are other metaprogramming techniques you might try to add the method. For example:

Tag.send(:define_method, "method_name") do 
  #code for your method
end

这篇关于如何在不编辑宝石来源的情况下将方法添加到红宝石宝石?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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