但是我得到一个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 methodendI 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 filesBut 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 methodend 这篇关于如何在不编辑宝石来源的情况下将方法添加到红宝石宝石?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!