Module: Sinatra::Mapping

Defined in:
lib/sinatra/mapping.rb

Overview

Copyright (c) 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.

Defined Under Namespace

Modules: Helpers

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#locationsObject (readonly)

All location paths mapped.



15
16
17
# File 'lib/sinatra/mapping.rb', line 15

def locations
  @locations
end

Class Method Details

.registered(app) ⇒ Object

Register automatically all helpers in base application.



71
72
73
# File 'lib/sinatra/mapping.rb', line 71

def self.registered(app)
  app.helpers Mapping::Helpers
end

Instance Method Details

#map(name, path = nil) ⇒ Object

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


27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/sinatra/mapping.rb', line 27

def map(name, path = nil)
  @locations ||= {}
  if name.to_sym == :root
    @locations[:root] = cleanup_paths("/#{path}/")
    metadef "#{name}_path" do |*paths|
      cleanup_paths("/#{@locations[:root]}/?")
    end
  else
    @locations[name.to_sym] = cleanup_paths(path || name.to_s)
    metadef "#{name}_path" do |*paths|
      map_path_to(@locations[name.to_sym], *paths << "/?")
    end
  end
  Delegator.delegate "#{name}_path"
end

#mapping(hash) ⇒ Object

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 "mapping.yml".
root: tasks
status: changes

# In Sinatra application.

mapping YAML.load_file("mapping.yml")
#=> root_path   # /tasks
#=> status_path # /tasks/changes


64
65
66
67
68
# File 'lib/sinatra/mapping.rb', line 64

def mapping(hash)
  hash.each do |name, path|
    map name, path
  end
end