2013-03-04 112 views
5
json = JSON.parse(response.body) 
    @games = json['machine-games'] 

    paging = json['paging'] 
    if paging 
     if paging['next'] 
     next_page_query = paging['next'].match(/\?.*/)[0] 
     @next_page = "/machine_games/search#{next_page_query}" 
    end 

    if paging['previous'] 
     previous_page_query = paging['previous'].match(/\?.*/)[0] 
     @previous_page = "/machine_games/search#{previous_page_query}" 
    end 
    end 

以上是從在controller.How顯示方法的一小塊邏輯的做我將其移動到演示者,使得其將保持machine_games JSON響應和提供方法來訪問遊戲和下一頁/上一頁的鏈接(以及它們是否存在)。 {不熟悉使用Presenter模式}使用演示

回答

14

讓我們創建一個演示者,將JSON響應解析爲@games,@next_page@previous_page

# app/presenters/games_presenter.rb 

class GamesPresenter 

    attr_reader :games, :next_page, :previous_page 

    def initialize json 
    @games = json['machine-games'] 

    paging = json['paging'] 
    if paging && paging['next'] 
     next_page_query = paging['next'].match(/\?.*/)[0] 
     @next_page = "/machine_games/search#{next_page_query}" 
    end 

    if paging && paging['previous'] 
     previous_page_query = paging['previous'].match(/\?.*/)[0] 
     @previous_page = "/machine_games/search#{previous_page_query}" 
    end 
    end 

end 

現在你的控制器動作應該是這個樣子:

def show 
    # ... 
    @presenter = GamesPresenter.new(json) 
end 

而且你可以在你的看法使用它:

<% @presenter.games.each do |game| %> 
    ... 
<% end %> 

<%= link_to "Previous", @presenter.previous_page %> 
<%= link_to "Next", @presenter.next_page %> 

而且爲了告訴Rails加載應用程序/主持人/高配車型一起目錄/,控制器/,視圖/等內容添加到配置/ application.rb中:

config.after_initialize do |app| 
    app.config.paths.add 'app/presenters', :eager_load => true 
end 
+1

這真的很有幫助。謝謝:D – kauschan 2013-03-05 16:54:47