Syro

4. Matching booleans

4. Correspondance des booléens

So far we have learned how to match path segments with the on method by passing a string, and how to capture path segments by passing a symbol. The last use case for on is to evaluate the argument as a boolean, and run the block only if the argument is true. Note that I didn't say "truthy": the argument has to be equal to true, and anything else will evaluate to false.

Jusqu'ici on a appris comment matcher des segments de chemin avec la méthode on en lui passant une chaîne, et comment capturer le chemin de segments en lui passant un symbole. Le dernier cas d'utilisation de on c'est d'évaluer l'argument comme un booléen, et de n'exécuter le bloc que si l'argument esttrue. Notez que je n'ai pas dit "truthy": l'argument doit être égal à true, et tout autre valeur donnera false.

In the following example, the block will be executed only if the visitor arrived from a different website:

Dans l'exemple suivant, le bloc ne sera exécuté que si le visiteur arrive d'un autre site web :

  require "syro"

  App = Syro.new do
    on env["HTTP_REFERER"] != "" do
      get do
        res.text "I got #{env["HTTP_REFERER"]}"
      end
    end
  end

  env = {
    "REQUEST_METHOD" => "GET",
    "PATH_INFO"      => "/",
    "HTTP_REFERER"   => "http://example.com",
  }

  p App.call(env)

Run the code and you will get this output:

Exécutez le code et vous allez obtenir le résultat suivant :

  [200,
   {"Content-Length"=>"24",
    "Content-Type"=>"text/plain"},
   ["I got http://example.com"]]

Exercise

Exercice

Combine different matchers, nest them, and modify the env variable to get familiar with this approach of building applications.

Combinez différents matchers, imbriquez-les, et modifiez la variable env pour vous familiariser avec cette approche de construction d'applications.


Prev | Index | Next

Précédent | Sommaire | Suivant