A
A
Anton Ivanov2016-10-24 10:54:51
Ruby on Rails
Anton Ivanov, 2016-10-24 10:54:51

Why doesn't "not" work in constraints in rails routing?

Hello!
Here is the route.rb part:

Rails.application.routes.draw do
  authorized     = ->(request) { request.session[:user_id].present? }
  constraints !authorized do
    ...
  end

  constraints authorized do
    ...
  end
end

doesn't work like that. Routes from the first block always work. Even when there is a value in the session.
If you write the second lambda:
not_authorized = ->(request) { request.session[:user_id].blank? }
and "get involved" on it, then everything works.
Please tell me why is that?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Sidorov, 2016-10-24
@Fly3110

Your `authorized` is a lambda. That is, this is a function that will be executed every time the request comes to rails.
And this `!authorized`, this is the negation of the lambda, it will always be false. This is not a negation of the result of executing the lambda, it is a negation of the lambda object itself.

2.3.1 :001 > ->() { false }
 => #<Proc:[email protected](irb):1 (lambda)>
2.3.1 :002 > !(->() { false })
 => false

C
CapeRatel, 2016-10-25
@CapeRatel

authorized = request.session[:user_id].present? ? request.session[:user_id] : nil
if authorized
  Айди есть
else
  айди нет
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question