Class: Canson::Base

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Mustermann
Defined in:
lib/canson/base.rb

Overview

used to create a new app App < CansonBase

get '/foo' do
  {result: 'ok'}
end

end

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(responder = Responder.new) ⇒ Base

Returns a new instance of Base.



52
53
54
55
56
57
# File 'lib/canson/base.rb', line 52

def initialize(responder = Responder.new)
  @responder = responder
  @klass = self.class
  @websocket = nil
  @filename = File.expand_path('./index.html')
end

Instance Attribute Details

#klassObject (readonly)

Returns the value of attribute klass.



18
19
20
# File 'lib/canson/base.rb', line 18

def klass
  @klass
end

#responderObject

Returns the value of attribute responder.



19
20
21
# File 'lib/canson/base.rb', line 19

def responder
  @responder
end

Class Method Details

.routes(r = nil) ⇒ Object



46
47
48
49
# File 'lib/canson/base.rb', line 46

def routes(r = nil)
  return @routes = r if r
  @routes ||= Hash.new { |h, k| h[k] = RouteMap.new }
end

Instance Method Details

#call(env) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/canson/base.rb', line 63

def call(env)
  m = env['REQUEST_METHOD'].tr('/', '').downcase.to_sym
  target = routes[m][env['PATH_INFO']]

  if m == :get && env['PATH_INFO'] == '/' && File.file?(filename)
    out = File.open(filename)
    return [200, { 'X-Sendfile' => filename,
      'Content-Length' => out.size }, out]
  end

  return handle_socket(env) if env['HTTP_UPGRADE'] == 'websocket'
  return  [404, {}, ['no route']] unless target
  return call_result(env, target)
rescue => e
  puts e.message
  [500, {}, ["server error #{e.message}".to_json]]
end

#filenameObject



59
60
61
# File 'lib/canson/base.rb', line 59

def filename
  @filename
end

#handle_socket(env) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/canson/base.rb', line 81

def handle_socket(env)
  nickname = env['PATH_INFO'][1..-1].force_encoding 'UTF-8'
  if env['HTTP_UPGRADE'.freeze] =~ /websocket/i
    routes[:on_message][nickname] ||= Canson::Websocket.new(env)
    routes[:on_message][nickname].on_open = routes[:on_open]['websocket_method']
    routes[:on_message][nickname].on_close = routes[:on_close]['websocket_method']
    routes[:on_message][nickname].on_shutdown = routes[:on_shutdown]['websocket_method']
    routes[:on_message][nickname].on_message = routes[:on_message]['websocket_method']
    env['upgrade.websocket'.freeze] = routes[:on_message][nickname]
    return [0, {}, []]
  end
end