pandaZW pandaZW - 10 months ago 50
Ruby Question

Puzzled with constraints routes in rails

I am learning

.And here are some questions I can't understand.

class NamespaceConstraint
def self.matches?(request)
name = request.fullpath.split('/').second.downcase
if name[0] == '~' then name = name[1..-1] end
ns = Namespace.where(name_lower: request.fullpath.split('/').second.downcase).first
not ns.nil?

Rails.application.routes.draw do
constraints(NamespaceConstraint) do
get ':namespace' => 'namespaces#show'

  • What does these codes mean?

  • In
    means what?

  • This
    var wasn't defined,is
    creates it?

  • not ns.nil?
    This means what?

I am a complete beginner to ruby.
Thanks for helping me solving this.

max max
Answer Source

In self.matches?. ? means what?

In Ruby you can use far more characters then in most other languages when naming methods.

Among those are ? and !. They have no special meaning to the interpreter.

However the convention in the community is that methods ending in ? are interrogative. They tell you if something is true or false.

class Person
  attr_accessor :age

  def initialize(age = 0)
    @age = age

  def drinking_age?
    @age >= 18

This request var wasn't defined,is rails creates it?

request in this context is a method argument.

Inside the .matches? method the local variable request is whatever you have passed into the method.

Rails calls something like NamespaceConstraint.matches?(request)* when it checks if the incoming request matches your custom constraint.

The request object is created by the Rack middleware.

not ns.nil?

not is keyword that negates the following expression. Just like in english. ! is more commonly used due to precedence.

nil in ruby is nothing - a value that is not defined or has no value.

So .nil? tells you if a variable is nil. Every object in ruby responds to this method.

irb(main):007:0> 0.nil?
=> false
irb(main):008:0> false.nil?
=> false
irb(main):009:0> nil.nil?
=> true

So not ns.nil? translates to plain english as: is ns not nothing? or is ns anything?.


You're really out of you're depth. The only reason you would do something like this is if you where building a multi-tenant app - which is a hardly a task suited for a beginner.

First learn the basics of the Ruby language.

Then revisit Rails. Learning both a programming language and a framework at the same time is not a really good idea as you will mush both together mentally.