Class: WebFx

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

Constant Summary collapse

AsyncResponse =
[-1, {}, []].freeze

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/webfx.rb', line 104

def call(env)

  EventMachine::next_tick do
  
    request = Rack::Request.new(env)
      
    def static(type, file, env)
      begin
        body = DeferrableBody.new
        body.call [IO.read(file)]
        env['async.callback'].call [200, { 'Content-Type' => type, 'Cache-Control' => 'public, max-age=86400' }, body]
      rescue => e
        env['async.callback'].call [404, { 'Content-Type' => 'text/plain'}, 'Not found.']
      end
    end

    if request.path == '/'
      static('text/html', 'public/index.html', env)
    end

    if request.path.match(/(.*).js$/)
      static('text/javascript', "public/#{$1}.js", env)
    end

    if request.path.match(/(.*).css$/)
      static('text/css', "public/#{$1}.css", env)
    end

    if request.path.match(/(.*).jpg$/)
      static('image/jpg', ".#{$1}.jpg", env)
    end

    params = request.params
   
    if request.post?
      if not params['file']
        body = request.body.read
        params.merge!(JSON.parse(body)) if body != ''
      end
    end
         
    force_method = params['_method']
    if force_method
      method = force_method
      params.delete('_method')  
    else
      method = request.request_method
    end
    method.downcase!
                       
    me = @@authenticate ? @@authenticate.call(params) : nil
    ctx = Context.new(method, me, env, DeferrableBody.new)

    found = false
    
    @@routes[method].each do |item|
      if request.path[1..-1].match(item[:regexp])
        found = true
        case $~.length
          when 1 then item[:fn].call(params, ctx)
          when 2 then item[:fn].call($1, params, ctx)
          when 3 then item[:fn].call($1, $2, params, ctx)
          when 4 then item[:fn].call($1, $2, $3, params, ctx)
          when 5 then item[:fn].call($1, $2, $3, $4, params, ctx)
          else item[:fn].call($~, params, ctx)
        end                              
      end
    end
    
    ctx.respond [404, {'Content-Type' => 'text/plain'}, 'Not found.'] if not found
  end

  AsyncResponse 
end