干掉这个 httparty 代码并将其移出控制器并移入模型中
Dry up this httparty code and move it out of the controller and into the model
文章控制器
def home
@url = 'https://meta.discourse.org/latest.json'
@forum_data = HTTParty.get(@url).parsed_response
@topic_one = @forum_data['topic_list']['topics'][0]['title']
@topic_two = @forum_data['topic_list']['topics'][1]['title']
@topic_three = @forum_data['topic_list']['topics'][2]['title']
@topic_four = @forum_data['topic_list']['topics'][3]['title']
@topic_five = @forum_data['topic_list']['topics'][4]['title']
end
articles/home.html.erb
<div class="topics">
<ul>
<li>
<%= @topic_one %>
</li>
<li>
<%= @topic_two %>
</li>
<li>
<%= @topic_three %>
</li>
<li>
<%= @topic_four %>
</li>
<li>
<%= @topic_five %>
</li>
</ul>
</div>
我正在为如何将整数作为变量传递给对象而苦苦思索,我也在为如何创建一个方法将其移入模型而苦苦思索。
你可以用 PORO 包装它:
class ForumTopicList
def initialize(discourse_forum_url)
@forum_url = discourse_forum_url
@forum_data = HTTParty.get(@url).parsed_response
end
def topics
@forum_data['topic_list']['topics'].map { |topic| ForumTopic.new(topic) }
end
class ForumTopic
def initialize(topic_hash)
@topic_hash = topic_hash
end
def title
@topic_hash['title']
end
end
end
这将允许您将控制器减少到:
def home
url = 'https://meta.discourse.org/latest.json'
@topics = ForumTopicList.new(url).topics.first(5)
end
你的观点可以变成
<div class="topics">
<ul>
<%= @topics.each do |topic|>
<li> <%= topic.title %> </li>
</ul>
</div>
文章控制器
def home
@url = 'https://meta.discourse.org/latest.json'
@forum_data = HTTParty.get(@url).parsed_response
@topic_one = @forum_data['topic_list']['topics'][0]['title']
@topic_two = @forum_data['topic_list']['topics'][1]['title']
@topic_three = @forum_data['topic_list']['topics'][2]['title']
@topic_four = @forum_data['topic_list']['topics'][3]['title']
@topic_five = @forum_data['topic_list']['topics'][4]['title']
end
articles/home.html.erb
<div class="topics">
<ul>
<li>
<%= @topic_one %>
</li>
<li>
<%= @topic_two %>
</li>
<li>
<%= @topic_three %>
</li>
<li>
<%= @topic_four %>
</li>
<li>
<%= @topic_five %>
</li>
</ul>
</div>
我正在为如何将整数作为变量传递给对象而苦苦思索,我也在为如何创建一个方法将其移入模型而苦苦思索。
你可以用 PORO 包装它:
class ForumTopicList
def initialize(discourse_forum_url)
@forum_url = discourse_forum_url
@forum_data = HTTParty.get(@url).parsed_response
end
def topics
@forum_data['topic_list']['topics'].map { |topic| ForumTopic.new(topic) }
end
class ForumTopic
def initialize(topic_hash)
@topic_hash = topic_hash
end
def title
@topic_hash['title']
end
end
end
这将允许您将控制器减少到:
def home
url = 'https://meta.discourse.org/latest.json'
@topics = ForumTopicList.new(url).topics.first(5)
end
你的观点可以变成
<div class="topics">
<ul>
<%= @topics.each do |topic|>
<li> <%= topic.title %> </li>
</ul>
</div>