Class: Kiss::Request

Inherits:
Object show all
Defined in:
lib/kiss/request.rb

Instance Method Summary collapse

Constructor Details

#initialize(env, controller, passed_config = {}) ⇒ Request

Processes and responds to a request. Returns array of response code, headers, and body.



12
13
14
15
16
17
# File 'lib/kiss/request.rb', line 12

def initialize(env, controller, passed_config = {})
  @_controller = controller
  @_config = passed_config
  
  @_files_cached_this_request = {}
end

Instance Method Details

#app_url(options = {}) ⇒ Object

Returns URL/URI of app root (corresponding to top level of action_dir).



378
379
380
381
382
383
384
# File 'lib/kiss/request.rb', line 378

def app_url(options = {})
  @_controller.app_url({
    :protocol => @_protocol,
    :host => @_app_host,
    :uri => @_app_uri
  }.merge(options))
end

#call(env) ⇒ Object



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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/kiss/request.rb', line 19

def call(env)
  @_env = env
  
  if @_controller.rack_file && (
    (env["PATH_INFO"] == '/favicon.ico') ||
    (env["PATH_INFO"].sub!(/\A#{@_controller.asset_uri}/, ''))
  )
    return @_controller.rack_file.call(env)
  elsif env["PATH_INFO"] =~ /favicon\.\w{3}\Z/
    return [404, {'Content-type' => 'text/html'}, 'File not found']
  end
  
  @_request = Rack::Request.new(env)
  
  @_protocol, @_app_host = (@_request.server.split(/\:\/\//, 2) rescue ['', ''])
  @_app_host = @_config[:app_host] if @_config[:app_host]
  @_app_uri = @_config[:app_uri] || @_request.script_name || ''
  
  @_host ||= @_request.host rescue ''
  
  # unfreeze path
  @_path = "#{@_request.path_info}" || '/'
  
  # remove extra path noise +[..][R]+GET...
  @_path.sub!(/\++(\[.*?\]\+*)*\[R\].*/, '')
  
  @_params = @_request.params
  @_query_string = @_request.query_string
  
  # catch and report exceptions in this block
  status_code, headers, body = handle_request(@_path, @_params)
  
  if body.respond_to?(:prepend_html)
    unless @_debug_messages.empty?
      extend Kiss::Debug
      body = prepend_debug(body)
    
      headers['Content-Type'] = 'text/html'
      headers['Content-Length'] = body.content_length.to_s
    end
  
    unless @_benchmarks.empty?
      stop_benchmark
      extend Kiss::Bench
      body = prepend_benchmarks(body)
      headers['Content-Type'] = 'text/html'
      headers['Content-Length'] = body.content_length.to_s
    end
  end
  
  return_database if @_db

  [status_code, headers, body]
end

#check_evolution_number(db) ⇒ Object

Check whether there exists a file in evolution_dir whose number is greater than app’s current evolution number. If so, raise an error to indicate need to apply new evolutions.



245
246
247
248
249
250
251
252
253
# File 'lib/kiss/request.rb', line 245

def check_evolution_number(db)
  db_version = db.evolution_number
  if @_controller.directory_exists?(@_controller.evolution_dir) && @_controller.evolution_file(db_version+1)
    raise <<-EOT
  database evolution number #{db_version} < last evolution file number #{@_controller.last_evolution_file_number}
  apply evolutions or set database evolution number
  EOT
  end
end

#cookiesObject



427
428
429
# File 'lib/kiss/request.rb', line 427

def cookies
  request.cookies
end

#databaseObject Also known as: db

Acquires and returns a database connection object from the connection pool.

Tip: ‘db’ is a shorthand alias for ‘database’.



215
216
217
218
219
220
221
222
# File 'lib/kiss/request.rb', line 215

def database
  @_db ||= begin
    db = @_controller.database
    check_evolution_number(db)
    db.kiss_request = self
    db
  end
end

#debug(object, context = ) ⇒ Object Also known as: trace

Adds debug message to inspect object. Debug messages will be shown at top of application response body.



348
349
350
351
# File 'lib/kiss/request.rb', line 348

def debug(object, context = Kernel.caller[0])
  @_debug_messages.push( [object.inspect.gsub(/  /, ' &nbsp;'), context] )
  object
end

#exception_cache(data = nil) ⇒ Object Also known as: set_exception_cache

Adds data to be displayed in “Cache” section of Kiss exception reports.



410
411
412
413
# File 'lib/kiss/request.rb', line 410

def exception_cache(data = nil)
  @_exception_cache.merge!(data) if data
  @_exception_cache
end

#file_cache(path, *args, &block) ⇒ Object

If file has already been cached in handling the current request, retrieve from cache and do not check filesystem for updates. Else cache file via controller’s file_cache.



202
203
204
205
206
207
# File 'lib/kiss/request.rb', line 202

def file_cache(path, *args, &block)
  return @_controller.file_cache[path] if @_files_cached_this_request[path]
  @_files_cached_this_request[path] = true

  @_controller.file_cache(path, *args, &block)
end

#finalize_sessionObject

Saves session to session store, if session data has changed since load.



291
292
293
# File 'lib/kiss/request.rb', line 291

def finalize_session
  @_session.save if @_session_fingerprint != Marshal.dump(@_session.data).hash
end

#get_action(path, params) ⇒ Object

Parses request URI to determine action path and arguments, then instantiates action class to create action handler.



190
191
192
193
194
195
# File 'lib/kiss/request.rb', line 190

def get_action(path, params)
  @@action_class ||= Kiss::Action.get_root_class(@_controller, @_controller.action_dir)
  
  # return action handler (instance of action class)
  @@action_class.action_instance_for_path(path, self, params)
end

#handle_exception(e) ⇒ Object



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
# File 'lib/kiss/request.rb', line 116

def handle_exception(e)
  @_exception_messages = []
  
  report = Kiss::ExceptionReport.generate(e, @_env, @_exception_cache, @_db ? @_db.last_query : nil)
  exception_message = e.message.sub(/\n.*/m, '')
  
  if @_controller.exception_log_file
    @_controller.exception_log_file.print(report + "\n--- End of exception report --- \n\n")
  end
  
  status_code = 500
  body = report
  
  result = [status_code, {
    "Content-Type" => "text/html",
    "Content-Length" => body.content_length.to_s,
    "X-Kiss-Error-Type" => e.class.name,
    "X-Kiss-Error-Message" => exception_message
  }, body]
  
  should_send_exception_email = true
  
  unless @_loading_exception_handler
    @_loading_exception_handler = true
    begin
      exception_handler = lookup_exception_handler(e)
      if exception_handler
        should_send_exception_email = exception_handler[:send_email]
        new_result = load_exception_handler(exception_handler) 
        if exception_handler[:action]
          result = handle_request(exception_handler[:action])
          result[0] = exception_handler[:status_code] || 500
        end
      end
    rescue StandardError, LoadError, SyntaxError => e
      result = handle_exception(e)
    end
  end
  
  if should_send_exception_email && !@_controller.exception_mailer_config.empty?
    app_name = @_controller.exception_mailer_config.app_name ||
      @_controller.exception_mailer_config.app || 'Kiss'
    email_message = <<-EOT
Subject: #{app_name} - #{e.class.name}#{exception_message.blank? ? '' : ": #{exception_message}"}
Content-type: text/html

#{report}
EOT
    send_email(@_controller.exception_mailer_config.merge(:message => email_message))
    @_exception_email_sent = true
  end
  
  result
end

#handle_request(path, params = {}) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/kiss/request.rb', line 78

def handle_request(path, params = {})
  begin
    @_exception_cache = {}
    @_debug_messages = []
    @_benchmarks = []
    @_response = Rack::Response.new
  
    catch :kiss_request_done do
      action = invoke_action(path, params)
      extension = action.extension
      options = action.output_options
      
      if content_type = options[:content_type] || (extension ? Kiss.mime_type(extension) : nil)
        @_response['Content-Type'] = "#{content_type}; #{options[:document_encoding] || 'utf-8'}"
      end
    
      send_response(action.output, options)
    end
    
    finalize_session if @_session
    @_response.finish
  rescue StandardError, LoadError, SyntaxError => e
    handle_exception(e)
  end
end

#invoke_action(path, params = {}, render_options = {}) ⇒ Object

ACTION METHODS #####



174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/kiss/request.rb', line 174

def invoke_action(path, params = {}, render_options = {})
  action = get_action(path, params)
  
  catch :kiss_action_done do
    action.authenticate if action.class.authentication_required
    
    action.before_call
    action.call
    action.render(render_options)
  end
  action.after_call
  action
end

#load_exception_handler(exception_handler) ⇒ Object



114
# File 'lib/kiss/request.rb', line 114

def load_exception_handler(exception_handler); end

#loginObject

Returns a Kiss::Login object containing data from session.login.



296
297
298
# File 'lib/kiss/request.rb', line 296

def 
  @_login ||= Kiss::Login.new(session)
end

#lookup_exception_handler(e) ⇒ Object



104
105
106
107
108
109
110
111
112
# File 'lib/kiss/request.rb', line 104

def lookup_exception_handler(e)
  klass = e.class
  while klass
    break if controller.exception_handlers[klass]
    klass = klass.superclass
  end
  
  klass && controller.exception_handlers[klass]
end

#modelsObject Also known as: dbm

Kiss Model cache, used to invoke and store Kiss database models.

Example: models == database model for ‘users’ table

Tip: ‘dbm’ (stands for ‘database models’) is a shorthand alias for ‘models’.



236
237
238
239
240
# File 'lib/kiss/request.rb', line 236

def models
  # make sure we have a database connection
  # create new model cache unless exists already
  db.kiss_model_cache
end

#new_email(options = {}) ⇒ Object

Returns new Kiss::Mailer object using specified options.



417
418
419
420
421
# File 'lib/kiss/request.rb', line 417

def new_email(options = {})
  controller.new_email({
    :request => self
  }.merge(options))
end

#path_infoObject



435
436
437
# File 'lib/kiss/request.rb', line 435

def path_info
  @_request.env["PATH_INFO"]
end

#path_with_query_stringObject



74
75
76
# File 'lib/kiss/request.rb', line 74

def path_with_query_string
  @_path + (@_query_string.empty? ? '' : '?' + @_query_string)
end

#pub_url(options = {}) ⇒ Object Also known as: asset_url

Returns URL/URI of app’s static assets (asset_host or public_uri).



387
388
389
390
391
392
393
394
395
# File 'lib/kiss/request.rb', line 387

def pub_url(options = {})
  if options.empty?
    @_pub ||= (@_controller.asset_host ? @_protocol + '://' + @_controller.asset_host : '') +
      (options[:uri] || @_controller.asset_uri || '')
  else
    (options[:protocol] || @_protocol) + '://' + (options[:host] || @_controller.asset_host) + 
      (options[:uri] || @_controller.asset_uri || '')
  end
end

#query_string_with_params(params = {}) ⇒ Object



398
399
400
401
402
403
# File 'lib/kiss/request.rb', line 398

def query_string_with_params(params = {})
  params = @_request.GET.merge(params)
  params.keys.map do |key|
    "#{key.to_s.url_escape}=#{params[key].to_s.url_escape}"
  end.join('&')
end

#redirect_action(action, options = {}) ⇒ Object

Redirects to specified action path, which may also include arguments.



335
336
337
338
339
340
341
# File 'lib/kiss/request.rb', line 335

def redirect_action(action, options = {})
  redirect_url( app_url(options) + action + (options[:params] ?
    '?' + options[:params].keys.map do |k|
      "#{k.to_s.url_escape}=#{options[:params][k].to_s.url_escape}"
    end.join('&') : '')
  )
end

#redirect_url(url) ⇒ Object

Sends HTTP 302 response to redirect client browser agent to specified URL.



326
327
328
329
330
331
332
# File 'lib/kiss/request.rb', line 326

def redirect_url(url)
  @_response.status = 302
  @_response['Location'] = url
  @_response.body = ''

  throw :kiss_request_done
end

#return_databaseObject



225
226
227
228
# File 'lib/kiss/request.rb', line 225

def return_database
  @_db.kiss_request = nil
  @_controller.return_database(@_db)
end

#send_email(options = {}) ⇒ Object



423
424
425
# File 'lib/kiss/request.rb', line 423

def send_email(options = {})
  new_email(options).send
end

#send_file(path, options = {}) ⇒ Object

Outputs a Kiss::StaticFile object as response to Rack. Used to return static files efficiently.



305
306
307
308
309
# File 'lib/kiss/request.rb', line 305

def send_file(path, options = {})
  @_response = Kiss::StaticFile.new(path, options)
  
  throw :kiss_request_done
end

#send_response(output = '', options = {}) ⇒ Object

Prepares Rack::Response object to return application response to Rack.



312
313
314
315
316
317
318
319
320
321
322
323
# File 'lib/kiss/request.rb', line 312

def send_response(output = '', options = {})
  @_response['Content-Length'] = output.content_length.to_s
  @_response['Content-Type'] = options[:content_type] if options[:content_type]
  if options[:filename]
    @_response['Content-Disposition'] = "#{options[:disposition] || 'inline'}; filename=#{options[:filename]}"
  elsif options[:disposition]
    @_response['Content-Disposition'] = options[:disposition]
  end
  @_response.body = output
  
  throw :kiss_request_done
end

#sessionObject

Retrieves or generates session data object, based on session ID from cookie value.



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/kiss/request.rb', line 259

def session
  @_session ||= begin
    @_controller.session_class ? begin
      @_controller.session_setup ||= begin
        # setup session storage
        @_controller.session_class.setup_storage(self)
        true
      end
    
      session = @_controller.session_class.persist(self, @_request.cookies[@_controller.cookie_name])
      @_session_fingerprint = Marshal.dump(session.data).hash

      cookie_vars = {
        :value => session.values[:session_id],
        :path => @_config[:cookie_path] || @_app_uri,
        :domain => @_config[:cookie_domain] || @_request.host
      }
      cookie_lifespan = @_config[:cookie_lifespan]
      if cookie_lifespan
        cookie_lifespan = eval(cookie_lifespan) if cookie_lifespan.is_a?(String)
        cookie_vars[:expires] = Time.now + cookie_lifespan
      end

      # set_cookie here or at render time
      @_response.set_cookie @_controller.cookie_name, cookie_vars
  
      session
    end : {}
  end
end


431
432
433
# File 'lib/kiss/request.rb', line 431

def set_cookie(*args)
  response.set_cookie(*args)
end

#start_benchmark(label = nil, context = ) ⇒ Object Also known as: bench

Starts a new benchmark timer, with optional label. Benchmark results will be shown at top of application response body.



356
357
358
359
360
361
362
363
# File 'lib/kiss/request.rb', line 356

def start_benchmark(label = nil, context = Kernel.caller[0])
  stop_benchmark(context)
  @_benchmarks.push(
    :label => label,
    :start_time => Time.now,
    :start_context => context
  )
end

#stop_benchmark(end_context = nil) ⇒ Object Also known as: bench_stop

Stops last benchmark timer, if still running.



367
368
369
370
371
372
# File 'lib/kiss/request.rb', line 367

def stop_benchmark(end_context = nil)
  if @_benchmarks[-1] && !@_benchmarks[-1][:end_time]
    @_benchmarks[-1][:end_time] = Time.now
    @_benchmarks[-1][:end_context] = end_context
  end
end

#url_with_params(params = {}) ⇒ Object



405
406
407
# File 'lib/kiss/request.rb', line 405

def url_with_params(params = {})
  "#{app_url}#{@_path}?#{query_string_with_params(params)}"
end