简体   繁体   中英

How do I add a method to a ruby gem without editing the gem source?

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

Wait, you shouldn't be adding method to the file , but to the class instead. Are you familiar with the concept of reopening the class ? You can't add a method just by naming your file same as the one which original class is defined in. Fortunately. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM