我应该把它变成一个模块吗?
在我的 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
的内容。
还有其他方法吗?寻找建议/文章。
In my Rails 3.1 app. Ive got a few controller's calling this block of code:
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
Instead of re-typing this block of code everywhere. Should I have this in a module instead? i.e. to keep things DRY?
If so, where should this go? I read somewhere about putting module code in app/concerns/foobar.rb
.
Any other approach? Looking for suggestions / articles.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最好不要重复您的代码。这样,当您更改某些内容时,只需在一处进行即可。 (相信我 - 您不想重复执行五次,然后只是希望您没有错过任何内容。)
将其放在所有控制器都可以访问它的地方。考虑为您可能需要的所有辅助方法创建一个模块(或文件夹)并将它们保存在一个位置。这样你就总知道该往哪里看。
it's always better not to repeat your code. That way when you change something, you only have to do it in one place. (And believe me - you don't want to do it five times over and then just hope you didn't miss anything.)
Put it somewhere where all the controllers can access it. Consider making a module (or a folder) for all the helper methods you might need and keep them in one place. That way you always know where to look.