Jill
Jill

Reputation: 533

How to edit a method of a gem?

I'm using the gem acts_as_commentable_with_threading, and I'd like to add something to the destroy method. Currently, if you delete a comment and it has replies it will delete the comment and it's replies. I'd like to keep this function only for the root comment, but not for the children. So if it is like this

     Comment 1
     /        \ 
     \      Comment 4
    Comment 2
       \
        \
      Comment 3

Where comment 2, 3, and 4 are all children of 1, but 3 is also a child of 2. I want to make it so that if you delete comment 2, comment 3 will still be there. However, keep it so that if Comment 1 is deleted then all of the comments under it are deleted because comment 1 is the root comment. So I have to edit the destroy method in the gem to allow this. How would I go about doing this? (Not really asking how to do the logic rather where can I edit the method, but I'd also appreciate help on the logic)

Upvotes: 0

Views: 184

Answers (1)

geej
geej

Reputation: 26

You can do this via monkey patching, which basically involves defining additional aspects of a class or module within another file. A good place to put this, I've found, is in config/initializers.

So, if you want to overwrite the destroy method of class A::B, you would make a file that says something like:

require 'loads_a_b'
module A
  class B
    def destroy_with_child_preservation
      # your code
    end
    alias_method_chain :destroy, :child_preservation
  end
end

And you can refer to the original method by calling destroy_without_child_preservation

Upvotes: 1

Related Questions