在我的Rails 3.1应用程序中。我有几个控制器调用这段代码:
twitter_entertainment_users = Rails.cache.fetch('twitter_entertainment_users', :expires_in => 24.hours) do
begin
Timeout.timeout(10.seconds) do
Twitter.suggestions('entertainment')
puts "#{Twitter.rate_limit_status.remaining_hits.to_s} Twitter API request(s) remaining this hour"
end
rescue Twitter::NotFound
end
end
而不是在任何地方重新输入这段代码。我应该在模块中使用它吗?即保持干燥?
如果是的话,这应该去哪儿了?我在某处读到了将模块代码放在app/concerns/foobar.rb
中的内容。
还有其他方法吗?寻找建议/文章。
答案 0 :(得分:0)
最好不要重复你的代码。这样,当你改变某些东西时,你只需要在一个地方做。 (相信我 - 你不想做五次,然后只希望你没有错过任何东西。)
把它放在所有控制器都可以访问它的地方。考虑为您可能需要的所有辅助方法创建一个模块(或文件夹),并将它们保存在一个位置。这样你总能知道在哪里看。