-
Notifications
You must be signed in to change notification settings - Fork 14
RoutingPlugin
This component provides Sinatra with an enhanced url routing system which enables named routes to be defined and used throughout your application. The benefits of this are that instead of having to hardcode your urls in every link and definition, instead you can define the url in a single spot and then attach a nickname which can be used to refer to the url in your application.
# app.rb
require 'sinatra/base'
require 'sinatra_more'
class Application < Sinatra::Base
# ...
register SinatraMore::RoutingPlugin
# ...
end
Basic named routes simply supply an alias symbol which represents a url string and accepts no query parameters. Let’s take a look at how to define the basic named route mappings:
# /app/routes/example.rb
class RoutingDemo < Sinatra::Application
# ...
# Define the named route mappings
map(:accounts).to("/the/accounts/index")
# Setup the routes using the named alias
get :accounts do
"I am the body for the url /the/accounts/index"
end
end
As shown above, simply define the route alias with map(:alias).to("url")
and then configure the route using the alias.
Once a route named alias has been defined, you can access that url using the alias anywhere in the application. To access the url for a given mapping, simply use url_for
such as:
url_for(:accounts)
Let’s try making a link referring to the url:
# /app/views/index.erb
<h1>This is a title</h1>
<p>Check out the #{link_to 'accounts page', url_for(:accounts)}</p>
This will generate a link to the accounts page with the url specified in the route mappings.
Named routes also support passing parameters to the routes. Let’s suppose we want to define a route for an account page which requires an id parameter. We would start by defining the alias:
# app/routes/example.rb
map(:account).to("/accounts/:id")
Now we can configure the route using the alias name:
# app/routes/example.rb
get :account do
"The id passed in is #{params[:id]}"
end
And finally we can access the route using url_for
:
link_to 'account', url_for(:account, :id => @account.id)
This plugin also supports name-spaced route mappings. These are mappings which are organized under a collective namespace
and may be helpful if you have a large application with multiple distinct parts. To define a namespaced route alias:
# app/routes/example.rb
map(:admin, :show).to("/admin/:id/show")
You can also define the namespaced route alias within a block:
# app/routes/example.rb
map :admin do |namespace|
namespace.map(:show).to("/admin/:id/show")
namespace.map(:destroy).to("/admin/:id/destroy")
end
You can then configure the route:
# app/routes/example.rb
namespace :admin do
get :show do
"admin show for #{params[:id]}"
end
get :destroy do
"admin destroy for #{params[:id]}"
end
end
And finally can access the url using the alias:
link_to 'admin with id', url_for(:admin, :show, :id => 25)
link_to 'admin with id', url_for(:admin, :destroy, :id => 25)