开发者

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

开发者 https://www.devze.com 2022-12-28 06:10 出处:网络
I need to override the behavior of the find method of a class from a gem. This is the code in the gem:

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 Co开发者_Go百科ntroller of my Rails Application?

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


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


I have elaborated such a solution which DOES NOT require the Rails server restart after every code change (unlike all the other's solutions):

1. Create YoutubeHelper.rb

module YoutubeHelper

  include Youtube

  def init_youtube_helper

    display.class_eval do
      def find(id, options = {})
      //Code here     
      end
    end

  end

end

2. youtube_search_controller.rb

class YoutubeSearchController < ActionController::Base
  include YoutubeHelper    
  before_action :init_youtube_helper   
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号