Search code examples
ruby-on-railsrubygemsmethodsoverriding

How to override a method of a class from a gem in Rails?


I need to override the behavior of the find method of a class from a gem.

This is the code in the gem:

module Youtube
  class Display
    attr_accessor :base
    def find(id, options = {})
      detailed = convert_to_number(options.delete(:detailed))
      options[:detailed] = detailed unless detailed.nil?
      base.send :get, "/get_youtube", options.merge(:youtube_id => id)
    end
  end
end

How do I override the above find method in my own YoutubeSearch Controller of my Rails Application?

   def find(id, options = {})
    //Code here     
   end

Solution

  • Create a .rb file in config/initializers directory with the following code:

    Youtube::Display.class_eval do
      def find(id, options = {})
        # Code here     
      end
    end