简体   繁体   English

您可以使用Timecop gem在Rails中进行开发吗?

[英]Can you use Timecop gem for development In Rails?

I found time travelling gems like Timecop, to test time dependent features. 我发现像Timecop这样的时光旅行宝石可以测试与时间相关的功能。 Is it possible and/or sensible to use this in development as well? 开发中也可以使用它吗?

If not: is there another time traveller gem, suitable for development? 如果不是:还有另一个适合发展的旅行者宝石吗? I couldn't find one. 我找不到一个。

Yes, sure you can. 是的,可以。 Here's some example code from an app I've built, where you can set a date via the admin area, and then browse the site as if it's that date, for the duration of your session: 这是我构建的应用程序中的一些示例代码,您可以在其中通过管理区域设置日期,然后在会话期间像浏览该日期一样浏览网站:

in app/controllers/concerns/time_travel_filters.rb : app/controllers/concerns/time_travel_filters.rb

# This allows us to set a different date
# in the admin area, and use TimeCop to process each
# request as being on that different date - useful for
# testing different phases of the challenge.
module TimeTravelFilters
  extend ActiveSupport::Concern

  included do
    if Rails.env.development? || Rails.env.staging?
      around_filter :time_travel_for_request
    end
  end

  def time_travel_for_request
    time_travel
    yield
    time_travel_return
  end

  def time_travel
    logger.info 'TIME TRAVEL START'
    if session[:timecop_date]
      Timecop.travel(session[:timecop_date])
    else
      Timecop.return
    end
  end

  def time_travel_return
    logger.info 'TIME TRAVEL RETURN'
    Timecop.return
  end
end

and then you just need to include TimeTravelFilters in your controllers that you want to use it. 然后您只需要在要使用它的控制器中include TimeTravelFilters

You'll need to set session[:timecop_date] in order for it to take effect - I do this through a form on a page in my admin area, but you can do it however you want. 您需要设置session[:timecop_date]才能生效-我通过管理区域页面上的表单来执行此操作,但是您可以根据需要进行设置。 Returning to the current time is as simple as deleting that session key. 返回当前时间就像删除该会话密钥一样简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM