Module Sinatra::Mapping

  1. lib/sinatra/mapping.rb

Copyright © 2009 Hallison Batista

This extension is useful for any Web application written using Sinatra DSL. The main goal is help developers to write URL path methods.

Methods

public class

  1. registered

public instance

  1. build_path_to
  2. map
  3. mapping

Classes and Modules

Module Sinatra::Mapping::Helpers

Attributes

locations [R] All location paths mapped.

Public class methods

registered (app)

Register automatically all helpers in base application.

[show source]
    # File lib/sinatra/mapping.rb, line 80
80:   def self.registered(app)
81:     app.helpers Mapping::Helpers
82:   end

Public instance methods

build_path_to (script_name = nil, *args)

Returns URL path with query instructions. This method has been extracted from wiki.github.com/sinatra/sinatra/howto-generate-links.

[show source]
    # File lib/sinatra/mapping.rb, line 71
71:   def build_path_to(script_name = nil, *args)
72:     args.compact!
73:     query = args.pop if args.last.kind_of?(Hash)
74:     path  = map_path_to(script_name, *args)
75:     path << "?" << Rack::Utils::build_query(query) if query
76:     path
77:   end
map (name, path = nil)

Write URL path method for use in HTTP methods.

The map method most be used by following syntax:

map <name>, <path>

If name is equal :root, then returns path ended by slash “/”.

map :root,    "tasks"       # => /tasks/
map :changes, "last-changes # => /tasks/last-changes
[show source]
    # File lib/sinatra/mapping.rb, line 27
27:   def map(name, path = nil)
28:     @locations ||= {}
29:     if name.to_sym == :root
30:       @locations[:root] = cleanup_paths("/#{path}/")
31:       metadef "#{name}_path" do |*paths|
32:         cleanup_paths("/#{@locations[:root]}/?")
33:       end
34:     else
35:       @locations[name.to_sym] = cleanup_paths(path || name.to_s)
36:       metadef "#{name}_path" do |*paths|
37:         map_path_to(@locations[name.to_sym], *paths << "/?")
38:       end
39:     end
40:   end
mapping (hash)

Auto mapping from a hash. This method is very useful. Example:

# In Web application.
class WebApp << Sinatra::Base
  mapping :root   => "tasks",   # /tasks
          :status => "changes"  # /tasks/changes
end

Or, it’s possible use from configuration file.

# YAML file "settings.yml".
mapping:
  root: tasks
  status: changes

# In Sinatra application.
mapping YAML.load_file("settings.yml")[:mapping]
# root_path   # /tasks
# status_path # /tasks/changes
[show source]
    # File lib/sinatra/mapping.rb, line 62
62:   def mapping(hash)
63:     hash.each do |name, path|
64:       map name, path
65:     end
66:   end