class Rack::TimeTraveler

Attributes

app[R]
options[R]

Public Class Methods

new(app, options = {}) click to toggle source
# File lib/rack/timetraveler.rb, line 7
def initialize(app, options = {})
  @app, @options = app, options

  default_fetcher = lambda { |env| fetch_from_env(env) }
  @options[:timestamp_fetcher] ||= default_fetcher

  @options[:enabled_environments] ||= [:development, :test]
end

Public Instance Methods

call(env) click to toggle source
# File lib/rack/timetraveler.rb, line 16
def call(env)
  return @app.call(env) unless enabled?

  time = validate_timestamp(env)

  return @app.call(env) if time.nil?

  Timecop.travel(time) { @app.call(env) }
end

Private Instance Methods

enabled?() click to toggle source
# File lib/rack/timetraveler.rb, line 28
def enabled?
  @options[:enabled_environments].map(&:to_s).include?(ENV['RACK_ENV'])
end
fetch_from_env(env) click to toggle source
# File lib/rack/timetraveler.rb, line 45
def fetch_from_env(env)
  env['HTTP_RACK_TIME_TRAVELER_TIMESTAMP'] ||
    env['RACK_TIME_TRAVELER_TIMESTAMP']
end
fetch_timestamp(env) click to toggle source
# File lib/rack/timetraveler.rb, line 40
def fetch_timestamp(env)
  fetcher = @options[:timestamp_fetcher]
  fetcher.call(env)
end
validate_timestamp(env) click to toggle source
# File lib/rack/timetraveler.rb, line 32
def validate_timestamp(env)
  timestamp = fetch_timestamp(env)
  return if timestamp.nil?
  Time.at(Integer(timestamp))
rescue
  nil
end