Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinatra Conditions

Tags:

ruby

sinatra

After studying ruby for about a month, I decided to move on to Sinatra. I need help understanding a Sinatra snippet which illustrates conditions and routing. Could someone clearly explain what's going on line-by-line and how this block is actually randomizing the route?

set(:probability) { |value| condition { rand <= value } }

  get '/win_a_car', :probability => 0.1 do
    "You won!"
  end

  get '/win_a_car' do
    "Sorry, you lost."
  end
like image 330
Dru Avatar asked Aug 14 '11 16:08

Dru


People also ask

What is Sinatra framework?

Sinatra is a Domain Specific Language implemented in Ruby that's used for writing web applications. Created by Blake Mizerany, Sinatra is Rack-based, which means it can fit into any Rack-based application stack, including Rails. It's used by companies such as Apple, BBC, GitHub, LinkedIn, and more.


1 Answers

The overall behavior of this will cause the first route to be loaded about 10% of the time and the 2nd route will be loaded the rest of the time.

The first route uses a condition set via probability. probability set above will pass its value and test to see if a random # between 0-1 is less than this probability value. Since the value is 0.1, it will return true 10% of the time.

The other 90% of the time the 2nd route will be called. The earlier routes take preference, the first valid route found will be called.

If you wanted to set the probability in another setting, you would need to defer the evaluation of the probability with a Proc.

Read more on conditional routes here: http://www.sinatrarb.com/intro#Conditions

like image 81
johnmartirano Avatar answered Oct 19 '22 00:10

johnmartirano