覆盖 rails 中的 gem 方法
Override gem method in rails
我想让用户添加兴趣-在这种情况下是电视节目-,并确保他们输入正确的电视节目,我将首先搜索 imdb 并让他们select其中一个returning 标题。
我发现这个 gem https://github.com/ariejan/imdb 几乎可以满足我的需要。如果我搜索 "The vampire diaries",它会 return 它和 200 个额外的匹配项。
我浏览了gem,发现他在这里做查询部分https://github.com/ariejan/imdb/blob/master/lib/imdb/search.rb。
def self.query(query)
open("http://akas.imdb.com/find?q=#{CGI.escape(query)};s=tt")
end
该查询基本上使用此 link http://akas.imdb.com/find?q= and returns everything that can find given the input - movies, tv shows, episodes. Now I found a more advanced query which uses type
and some other params. So I could actually return only 4 results in that case instead of 250. All I have to do is to replace that query with http://www.imdb.com/search/title?title=The%20Vampire%20Diaries&title_type=tv_series。
如何覆盖该搜索方法?
您可以重新打开class来覆盖方法:
class Imdb::Search
def self.query(query)
# your custom logic here
end
end
请注意,您可以在您的版本中调用 super(query)
以获得原始结果。
您可以使用class_eval并将其放在装饰器文件夹中
app/decorators/imdb/search_decorator.rb
class Imdb::Search.class_eval do
def self.query(query)
end
end
我想让用户添加兴趣-在这种情况下是电视节目-,并确保他们输入正确的电视节目,我将首先搜索 imdb 并让他们select其中一个returning 标题。
我发现这个 gem https://github.com/ariejan/imdb 几乎可以满足我的需要。如果我搜索 "The vampire diaries",它会 return 它和 200 个额外的匹配项。
我浏览了gem,发现他在这里做查询部分https://github.com/ariejan/imdb/blob/master/lib/imdb/search.rb。
def self.query(query)
open("http://akas.imdb.com/find?q=#{CGI.escape(query)};s=tt")
end
该查询基本上使用此 link http://akas.imdb.com/find?q= and returns everything that can find given the input - movies, tv shows, episodes. Now I found a more advanced query which uses type
and some other params. So I could actually return only 4 results in that case instead of 250. All I have to do is to replace that query with http://www.imdb.com/search/title?title=The%20Vampire%20Diaries&title_type=tv_series。
如何覆盖该搜索方法?
您可以重新打开class来覆盖方法:
class Imdb::Search
def self.query(query)
# your custom logic here
end
end
请注意,您可以在您的版本中调用 super(query)
以获得原始结果。
您可以使用class_eval并将其放在装饰器文件夹中
app/decorators/imdb/search_decorator.rb
class Imdb::Search.class_eval do
def self.query(query)
end
end