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
精彩评论