开发者

How to set class variables based on the current rails enviroment

I have a /lib/tasks/s开发者_运维技巧end_mailer_job.rb file.

On production I want that file to run every 5 minutes. When on dev however, waiting 5 minutes to test a change is slowing me down so I'd like that to be 1 minute. Lately I've just been updating the variable in the code but that is prone to errors as I could check-in the wrong # and kill the production servers. How can I set that variable based on the enviroment

I have the following:

 records = Stuff.find(:all, :conditions => ["last_activity_at <= ?", (Time.now - 500)])
 .....  1.minute.from_now

What's the right way to have those two #s, 500, and 1.minute.form_now be variable based on the rails environment, for dev I want shorter #s than on production & staging.

Thanks


Use Rails.env. Example below.

class Stuff < ActiveRecord::Base

  def self.latest
    time = Rails.env == "production" ? 5.minutes.from_now : 1.minute.from_now
    self.find(:all, :conditions => ["last_activity_at <= ?", time])
  end

end


Put the timestamp calculation into a method that uses Rails.env to choose the right delay:

class Stuff < ActiveRecord::Base
  def self.cutoff_time
    if Rails.env.production?
      5.minutes.ago
    else
      1.minute.ago
    end
  end
end

Then use this method in place of Time.now - 5.minutes wherever you need to compute the cutoff time. Putting it in a separate method like this also helps with testing since you can easily stub its return value to test various scenarios.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜