DEV Community

Igor Kasyanchuk
Igor Kasyanchuk

Posted on

Travel in time in development/staging/... in your Rails app

Hello,

I would like to share my new gem which myself and my QA team already found useful and maybe your team could find too.

https://github.com/igorkasyanchuk/rails_time_travel

The idea is very simple - sometimes you need to add data in the past, and overide Time.now.

I believe you already familiar with the gem https://github.com/travisjeffery/timecop which is very useful for testing.

And my gem is basically providing a simple UI to "control" current time (per user).

module RailsTimeTravel
  module Controller
    extend ActiveSupport::Concern

    included do
      around_action :time_travel_for_request
    end

    def time_travel_for_request
      time_travel
      yield
      time_travel_return
    end

    def time_travel
      if session[:timecop_date]
        logger.info "TIME TRAVEL START: #{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
end
Enter fullscreen mode Exit fullscreen mode

Most of the logic is simple and was taken from the stackoverflow, and only a simple control panel was codded to change datetime.

Time Travel Rails

To use this gem just add it to the Gemfile, bundle install and start the app. During start is adding ruby module above to the ApplicationController so this code will be executed on every request.

Once a server is running just open /rails/time_travel.

I hope you'll find it useful too!

Top comments (0)