简体   繁体   English

覆盖Rails中的gem方法

[英]Override gem method in rails

I want to let users add interests -TV shows in this case-, and to make sure they type a correct tv show, I'm going to search imdb first and let them select one of the returning titles. 我想让用户增加兴趣(在这种情况下为电视节目),并确保他们键入正确的电视节目,我将首先搜索imdb并让他们选择返回的标题之一。

I found this gem https://github.com/ariejan/imdb which is doing almost what I need. 我发现这个宝石https://github.com/ariejan/imdb几乎可以满足我的需求。 If I search for "The vampire diaries", it will return it and 200 extra matches. 如果我搜索“吸血鬼日记”,它将返回它和200个额外的匹配项。

I went through the gem and I found that he does the querying part here https://github.com/ariejan/imdb/blob/master/lib/imdb/search.rb . 我浏览了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

That query basically uses this link http://akas.imdb.com/find?q= and returns everything that can find given the input - movies, tv shows, episodes. 该查询基本上使用此链接http://akas.imdb.com/find?q=并返回在输入后可以找到的所有内容-电影,电视节目,剧集。 Now I found a more advanced query which uses type and some other params. 现在,我发现了一个更高级的查询,该查询使用type和其他一些参数。 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 . 因此,在那种情况下,我实际上只能返回4个结果,而不是250个。我要做的就是用http://www.imdb.com/search/title?title=The%20Vampire%20Diaries&title_type=tv_series替换该查询。

How do I override that search method? 如何覆盖该搜索方法?

You can use class_eval and put it in a decorators folder 您可以使用class_eval并将其放在装饰器文件夹中

app/decorators/imdb/search_decorator.rb

class Imdb::Search.class_eval do
  def self.query(query)
  end
end

You can re-open the class to override the method: 您可以重新打开该类以覆盖该方法:

class Imdb::Search
  def self.query(query)
    # your custom logic here
  end
end

Note that you can call super(query) in your version to get the result of the original. 请注意,您可以在您的版本中调用super(query)以获取原始结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM