Sinatra / Ruby default setting

Is there a way to set a parameter in Sinatra?

Currently I want to see if 'start' passed as a parameter, but it seems a bit hacky. It would be nice if I could tell Sinatra the default parameters if they are not specified.

 get '/comments/?' do # want to setup page stuff, default to first page if not specified params[:start] = 0 if !params[:start] end 

Any ideas?

+5
ruby sinatra
source share
2 answers

It’s true that you can use ||= in this way, but it’s very strange to tweak the parameters after they are extracted. Most likely, you will set the variables from the parameters. So instead:

 params[:start] ||= 0 

Of course, you are most likely to do this:

 start = params[:start] || 0 

and if you do, I suggest using fetch

 start = params.fetch :start, 0 

If you are really looking for default values ​​in parameter hashes before the route, use before the filter

 before "/comments/?" do params[:start] ||= 0 end 

Update:

If you take a parameter from a route template , you can give it a default argument using block parameters, because Ruby (from v1.9) can accept standard parameters for blocks, for example

 get "/comments/:start/?" do |start=0| # rest of code here end 

The start parameter will be available through the local start variable (indicated in the block) or through params[:captures].first (see the documents for more on routes ).


Further update:

When you pass a route to a verb method (such as get ), Sinatra will use this route to match incoming requests. Requests that match the fire indicated by the block, so an easy way to make it clear that you want to set default values:

 get "/comments/?" do defaults = {start: 10, finish: 20} params = defaults.merge params # more code follows… end 

If you want it to look cleaner, use a helper:

 helpers do def set_defaults( defaults={} ) warn "Entering set_defaults" # stringify_keys! h = defaults.each_with_object({}) do |(k,v),h| h[k.to_s] = defaults[k] end params.merge!( h.merge params ) end end get "/comments/?" do set_defaults start: 10, finish: 20 # more code follows… end 

If you need something heavier, try sinatra-param .


Sinatra :: Driver DefaultParameters

I really liked this bit of code. I turned it into a gem .

+4
source share

Here you can use the "or equal" operator: params[:start] ||= 0

http://www.rubyinside.com/what-rubys-double-pipe-or-equals-really-does-5488.html

+1
source share

All Articles