开发者

Should I turn this into a module?

开发者 https://www.devze.com 2023-04-08 10:18 出处:网络
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

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
      Twi开发者_StackOverflow社区tter.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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消