经过大量的实验和阅读的,这里是我结束了的情况下,任何人有兴趣:
我结束了在搜索模型和子模型代表了所有数据的混合方法,以及连接去客户端在lib文件夹中的模块中的第三方站点。
型号/ search.rb:
class Search
def initialize(params)
# code to start a new Search on third party site
@result = SearchApi.example_query(data_type_1_param)
# more code...
end
# other code to assist in parsing of search results
end
型号/搜索/ data_type_1.rb:
class Search::DataType1 < Hash
def initialize(DataModel1)
# code to convert DataModel1 to DataType1 for sending request
end
end
我也有其他几个搜索子模型,其类似于DataType1 。 此外,我创建了搜索子模型来表示搜索在程序中使用的易用性返回的数据,并具有一个抽象层。
型号/搜索/ results.rb:
class Search::Results
def initialize(result_hash)
@data = result_hash
end
def field_1
# code to parse and display field 1 from @data hash
end
def field_2
# code to parse and display field 2 from @data hash
end
#.... etc
end
搜索模型本身可能不是完全必要的(大多数的代码模块和子模型),但它方便地安装到MVC用于创建和显示搜索的框架。
最后,我创建了一个客户端类的模块,以实际联系第三方网站并进行搜索。虽然我可能已经能够将其包含在搜索模型中,但我需要此客户端持久化(出于多种原因)并处理多个搜索,同时为每个查询重新创建搜索模型。
lib/search_api。RB:
require 'search_api/client'
module SearchApi
class << self
def client
@client ||= SearchApi::Client.new()
@client
end
def example_query(data)
results = client.query(formatted_data)
# among other code
end
# other code to perform validations and interact with client
end
end
的lib/search_api/client.rb:
module SearchApi
class Client
include HTTParty
# code to create and handle connection to Search site
end
end
此方法可能不是每一个遵循最佳实践,并可能是矫枉过正了很多情况,但似乎摸出以及我正试图解决的问题。如果任何人有更好的想法来重构,我全都耳熟能详。