我应该把它变成一个模块吗?

发布于 2024-12-06 16:22:14 字数 560 浏览 3 评论 0原文

在我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

[旋木] 2024-12-13 16:22:14

最好不要重复您的代码。这样,当您更改某些内容时,只需在一处进行即可。 (相信我 - 您不想重复执行五次,然后只是希望您没有错过任何内容。)

将其放在所有控制器都可以访问它的地方。考虑为您可能需要的所有辅助方法创建一个模块(或文件夹)并将它们保存在一个位置。这样你就总知道该往哪里看。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文