How to override a class method of the gem in rails Application?

六眼飞鱼酱① 提交于 2019-12-17 23:39:38

问题


Best practice to Override a class method of the gem in rails Application ? . I need to override the behaviour of the find method of a gem.

following 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 YoutubeSearch Controller of Rails Application ?

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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/2688853/how-to-override-a-class-method-of-the-gem-in-rails-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!