问题
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