Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable rails route based on flag/constant

I've got a rails engine that has a simple constant defined in it.

require 'my_engine/engine'
module MyEngine
  OPEN_SIGNUPS = false
end

in my routes I have something like

if MyEngine::OPEN_SIGNUPS
  get 'sign_up'
else
  get 'request_access'
end

Basically if I haven't enabled the sign up feature, the user can request access to the beta.

Unfortunately this is proving really difficult to test bc I think the routes file is only loaded once (using rspec here). I tried stubbing out the constant with

stub_const("MyEngine::OPEN_SIGNUPS", true)

to test the open version, but I'm having issues getting it to work.

Is there a better way to have "conditional" routes based on a simple flag or constant. Some combination of constraints, perhaps? At this point I'm thinking of just adding ALL the routes and checking in each controller if OPEN_SIGNUPs isn't on, and redirect to the request access page if it isn't.

like image 798
typeoneerror Avatar asked Oct 31 '22 21:10

typeoneerror


1 Answers

You are correct, routes are only loaded once when your rails server is started, so what you have is only evaled on start. But you can add dynamic stuff using lambdas or any other function.

get 'signups', to: 'something#index', constraints: lambda{ |request| MyEngine::OPEN_SIGNUPS }

get 'request_access', to: 'other_thing#index', constraints: lambda{ |request| !MyEngine::OPEN_SIGNUPS }

Here is a link to advanced constaints. http://guides.rubyonrails.org/routing.html#advanced-constraints

Personally, i have only used constraints to restrict access to certain areas based on permissions. You may be better off to just have two routes and do a redirect in the controller based on the value in your module.

like image 124
Austio Avatar answered Nov 15 '22 05:11

Austio