Class: Nancy::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/nancy/base.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.call(env) ⇒ Object



53
54
55
# File 'lib/nancy/base.rb', line 53

def self.call(env)
  @builder.dup.call(env)
end

.compile(pattern) ⇒ Object



13
14
15
16
17
18
19
20
# File 'lib/nancy/base.rb', line 13

def self.compile(pattern)
  keys = []
  pattern.gsub!(/(:\w+)/) do |match|
    keys << $1[1..-1]
    "([^/?#]+)"
  end
  [%r{^#{pattern}$}, keys]
end

.inherited(child) ⇒ Object



46
47
48
49
50
51
# File 'lib/nancy/base.rb', line 46

def self.inherited(child)
  child.instance_eval do
    @builder = Rack::Builder.new
    @builder.run(child.new)
  end
end

.map(*args, &block) ⇒ Object



42
43
44
# File 'lib/nancy/base.rb', line 42

def self.map(*args, &block)
  @builder.map(*args, &block)
end

.route_setObject



22
23
24
# File 'lib/nancy/base.rb', line 22

def self.route_set
  @route_set ||= Hash.new { |h, k| h[k] = [] }
end

.use(*args, &block) ⇒ Object



38
39
40
# File 'lib/nancy/base.rb', line 38

def self.use(*args, &block)
  @builder.use(*args, &block)
end

Instance Method Details

#call(env) ⇒ Object



57
58
59
60
61
62
63
64
65
# File 'lib/nancy/base.rb', line 57

def call(env)
  Thread.current[:request] = Rack::Request.new(env)
  Thread.current[:response] = Rack::Response.new
  Thread.current[:params] = request.params
  Thread.current[:env] = env
  response = catch(:halt) do
    route_eval(request.request_method, request.path_info)
  end.finish
end

#halt(*res) ⇒ Object



82
83
84
85
86
87
88
89
# File 'lib/nancy/base.rb', line 82

def halt(*res)
  throw :halt, res.first if res.first.is_a?(Rack::Response)
  response.status = res.select{|x| x.is_a?(Fixnum)}.first || 200
  headers = res.select{|x| x.is_a?(Hash)}.first || {}
  response.header.merge!(headers)
  response.body = [(res.select{|x| x.is_a?(String)}.first || "")]
  throw :halt, response
end

#redirect(uri) ⇒ Object



34
35
36
# File 'lib/nancy/base.rb', line 34

def redirect(uri)
  halt 302, {"Location" => uri}
end

#route_eval(request_method, path_info) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/nancy/base.rb', line 67

def route_eval(request_method, path_info)
  path_info = "/" if path_info == ""
  self.class.route_set[request_method].each do |matcher, block|
    if match = path_info.match(matcher[0])
      if (captures = match.captures) && !captures.empty?
        url_params = Hash[*matcher[1].zip(captures).flatten]
        Thread.current[:params] = url_params.merge(params)
      end
      response.write instance_eval(&block)
      halt response
    end
  end
  halt 404
end

#sessionObject



30
31
32
# File 'lib/nancy/base.rb', line 30

def session
  request.env["rack.session"] || raise("Rack::Session handler is missing")
end