Module: Usher::Interface::Sinatra::Extension

Defined in:
lib/usher/interface/sinatra.rb

Class Method Summary collapse

Class Method Details

.included(cls) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/usher/interface/sinatra.rb', line 7

def self.included(cls)
  cls::Base.class_eval(<<-HERE_DOC, __FILE__, __LINE__)
    def self.route(verb, path, options={}, &block)
      @router ||= Usher.new(:request_methods => [:request_method, :host, :port, :scheme], :generator => Usher::Util::Generators::URL.new)

      name = options.delete(:name)
      options[:conditions] ||= {}
      options[:conditions][:request_method] = verb
      options[:conditions][:host] = options.delete(:host) if options.key?(:host)

      # Because of self.options.host
      host_name(options.delete(:host)) if options.key?(:host)

      define_method "\#{verb} \#{path}", &block
      unbound_method = instance_method("\#{verb} \#{path}")
      block =
        if block.arity != 0
          lambda { unbound_method.bind(self).call(*@block_params) }
        else
          lambda { unbound_method.bind(self).call }
        end

      invoke_hook(:route_added, verb, path, block)

      route = @router.add_route(path, options).to(block)
      route.name(name) if name
      route
    end          

    def self.router
      @router
    end

    def route!(base = self.class)
      if self.class.router and match = self.class.router.recognize(@request)
        @block_params = match.params.map{|p| p.last}
        @params = @params ? @params.merge(match.params_as_hash) : match.params_as_hash
        route_eval(&match.destination)
      elsif base.superclass.respond_to?(:routes)
        route! base.superclass
      else
        route_missing
      end
    end
    
    def generate(name, *params)
      self.class.router.generator.generate(name, *params)
    end

  HERE_DOC
end