Module Sinatra::Mapping::Helpers

  1. lib/sinatra/mapping.rb

This module contains several helper methods for paths written using map method.

Methods

public instance

  1. link_to
  2. path_to
  3. title_path

Public instance methods

link_to (name = nil, *args)

Creates anchor links for name and extract path and HTML options from arguments. Example:

# In Sinatra application, add a map.

map :tasks,  "tasks"
map :status, "tasks/status"

get tasks_path do
  erb :tasks, :locals => { :name => params.values.join(', ') }
end

get status_path do
  erb :status, :locals => { :status => "finished" }
end

# In status view, add a link to status map.

<%= link_to "All finished", :status, status %>
# => <a href="/tasks/status/finished">All finished</a>

<%= link_to "All finished", :status, :name => status %>
# => <a href="/tasks/status?name=finished">All finished</a>
[show source]
     # File lib/sinatra/mapping.rb, line 166
166:     def link_to(name = nil, *args)
167:       options = args.last.kind_of?(Hash) ? args.pop : {}
168:       url     = args.shift if args.first.to_s =~ /^\w.*?:/
169:       args   << extract_query_attributes(options)
170:       "<a href=\"#{url || path_to(*args)}\"#{extract_link_attributes(options)}>#{name || url}</a>"
171:     end
path_to (*args)

Returns all paths with query parameters. Example:

# In Sinatra application:

map :post, "articles"
map :tags, "labels"

# Use the following instructions:

path_to :tags, "ruby", :posts
# => "/labels/ruby/articles"
[show source]
     # File lib/sinatra/mapping.rb, line 184
184:     def path_to(*args)
185:       options.build_path_to(env['SCRIPT_NAME'], *args)
186:     end
title_path (path, *args)

Creates a title using a path mapped. Otherwise, returns just arguments joined by spaces and capitalised.

# In Sinatra application

map :posts,   "articles"
map :tags,    "labels"
map :archive, "archive/articles"

# In views

<%=title_path :posts%>
# => "Articles"

<%=title_path :tags%>
# => "Labels"

<%=title_path :archive%>
# => "Archive articles"
[show source]
     # File lib/sinatra/mapping.rb, line 137
137:     def title_path(path, *args)
138:       title = (options.locations[path] || path).to_s.gsub('/',' ').strip
139:       title.gsub!(/\W/,' ') # Cleanup
140:       (args.empty? ? title : "#{title} #{args.join(' ')}").strip.capitalize
141:     end