Time based routing for Rails

Dienstag, 17. November 2015, 10:30 Uhr | roberto@vasquez-angel.de |

If you want to add routes in rails, based on a timeframe, you can do this as follows:

In config/routes.rb

  scope constraints: lambda { |request| TimeRoutingConstraint.new('18.11.2015 18:00', '17.12.2015 00:00').matches?(request) } do
    get 'gewinnspiel', to: 'contest/registrations#new',
                       as: 'new_contest_registration'

    mount Contest::Engine, at: '/contest'
  end
  get 'gewinnspiel', to: 'contest/registrations#closed'

In app/routing_constraints/time_routing_constraint.rb

class TimeRoutingConstraint
  def initialize(from, to)
    @from = Time.zone.parse(from)
    @to   = Time.zone.parse(to)
  end

  def matches?(request)
    now = Time.zone.now
    if now > @from && now < @to
      true
    else
      false
    end
  end
end