| Module | Sinatra::Dsl |
| In: |
lib/sinatra/dsl.rb
|
Run given block after each Event‘s execution Example:
after_attend do
logger.debug "After event attend!"
end
or
after_attend :clean_up # clean_up is a helper method defined using helpers
# File lib/sinatra/dsl.rb, line 85
85: def after_attend(filter_name = nil, &block)
86: Sinatra::Event.after_attend(filter_name, &block)
87: end
Run given block after each Event‘s execution Usage:
before_attend do
logger.debug "After event attend!"
end
or
before_attend :authorize # authorize is a helper method defined using helpers
Stop execution using - throw :halt
before_attend do
throw :halt, 401 unless has_access?
end
Throw a Symbol to execute a helper method Throw a String to render it as the content Throw a Fixnum to set the status
# File lib/sinatra/dsl.rb, line 73
73: def before_attend(filter_name = nil, &block)
74: Sinatra::Event.before_attend(filter_name, &block)
75: end
Execute block if in environment is equal to env (Used for configuration)
# File lib/sinatra/dsl.rb, line 118
118: def config_for(env = :development)
119: yield if Sinatra::Options.environment == env.to_sym
120: end
Define an Event that responds to a path on GET method
The path can be a template (i.e. ’/:foo/bar/:baz’). When recognized, it will add :foo and :baz to params with their values.
Example:
# Going RESTful
get '/' do
.. show stuff ..
end
post '/' do
.. add stuff ..
redirect '/'
end
put '/:id' do
.. update params[:id] ..
redirect '/'
end
delete '/:id' do
.. delete params[:id] ..
redirect '/'
end
BIG NOTE: PUT and DELETE are trigged when POSTing to their paths with a _method param whose value is PUT or DELETE
# File lib/sinatra/dsl.rb, line 34
34: def get(path, &block)
35: Sinatra::Event.new(:get, path, &block)
36: end
Add methods to each event for use during execution
Example:
helpers do
def foo
'foo!'
end
end
get '/bar' do
foo
end
get_it '/bar' # => 'foo!'
# File lib/sinatra/dsl.rb, line 104
104: def helpers(&block)
105: Sinatra::EventContext.class_eval(&block)
106: end
Define named layouts (default name is :layout)
Examples:
# Default layout in Erb
layout do
'-- <%= yield %> --'
end
# Named layout in Haml
layout :for_haml do
'== XXXX #{yield} XXXX'
end
# Loads layout named <tt>:"foo.erb"</tt> from file (default behaviour if block is omitted)
layout 'foo.erb' # looks for foo.erb. This is odd an is being re-thought
def layout(name = :layout, options = {})
Layouts[name] = unless block_given?
File.read("%s/%s" % [options[:views_directory] || 'views', name])
else
yield
end
end
Cool trick:
# Send a one-time layout to renderer method
get '/cooltrick' do
erb 'wicked' do
'Cool <%= yield %> Trick'
end
end
get_it '/cooltrick' # => 'Cool wicked Trick'
# File lib/sinatra/dsl.rb, line 157
157: def layout(name = :layout, options = {})
158: Layouts[name] = unless block_given?
159: File.read("%s/%s" % [options[:views_directory] || 'views', name])
160: else
161: yield
162: end
163: end