2017-07-08 43 views
0

我正在使用RubyGems API Wrapper來獲取匹配名稱的寶石。我將搜索查詢提交給API,然後想要篩選響應以精確選擇與查詢匹配的gem(第一個gem並不總是最佳匹配)。我建立了我的控制器,就像這樣:在哪裏添加用於處理API響應的Rails控制器的方法?

class GemsController < ApplicationController 

    def show 
     gems = Gems.search(params[:name]) # From RubyGems Wrapper 
     @gem = exact_name_match?(gems, params[:name]) # My own method 
     if @gem 
      render json: { name: @gem["name"], info: @gem["info"], dependencies: @gem["dependencies"] }, status: :ok 
     else 
      render json: { errors: ["Gem not found"] }, status: :not_found 
     end 
    end 
end 

我試圖保持控制器瘦越好,所以我寫了一個方法,但exact_name_match?我不知道放在哪裏。我已經閱讀過有關服務對象的內容,但對於這種情況,這些看起來有些複雜。

注:我沒有數據庫或模型,因爲我只是使用API​​。

回答

0

我發現術語服務對象聽起來好像比它更多。它真的只是一個普通的Ruby對象。你可以創建一個類(像因爲app/*app/services/gem_finder.rb文件是自動加載)封裝你有這樣的尋找行爲:

class GemFinder 
    def initialize(name) 
     @name = name 
    end 

    def exact_name_match 
     gems.find { |gem| @name == gem['name'] } 
    end 

    private 

    def gems 
     @gems ||= Gems.search(@name) 
    end 
end 

這可能會在你的控制器中使用像這樣:

class GemsController < ApplicationController 

    def show 
     gem_finder = GemFinder.new(params[:name]) 
     if @gem = gem_finder.exact_name_match 
      render json: { name: @gem["name"], info: @gem["info"], dependencies: @gem["dependencies"] }, status: :ok 
     else 
      render json: { errors: ["Gem not found"] }, status: :not_found 
     end 
    end 
end 

這是有利的,因爲它將控制器從API封裝中分離出來。如果你需要在其他地方使用這種行爲,那麼gem搜索的所有邏輯都包含在這裏。如果包裝本身有更新,則只需要更改此類中的代碼。

+0

對不起,我應該提到,我沒有數據庫或模型。我嚴格使用RubyGems API。 – fafafariba

+0

啊,呃。我會更新我的答案! – dlachasse

相關問題