Class: Maveric::Controller

Inherits:
Object
  • Object
show all
Defined in:
lib/maveric.rb,
lib/maveric/sessions.rb

Overview

Controllers are the classes that do the actual handling and processing of requests. The number of normal methods is kept low to prevent clobbering by user defined methods.

Placing a Controller

They may be defined in any location, but if they are defined in a nested location within the Maveric class being used to serve at a particular location, on instantialization of the Maveric they will automatically be added at either the routes specified in their class definition or at the default route which is derived from their name and their nesting.

Working in Controller

Within an instance of Controller: @env contains the environment hash; @in contains the request body, and @cookies contains a hash of cookie values.

In addition @status, @header, and @body may be set to appropriate values for the response. Note that @headers should be a Hash, @status should be an Integer corresponding to a real HTTP status code, and @body should contain a String.

Those are the only instance variables you should be warned against playing with frivously.

Constant Summary collapse

REQUEST_METHODS =

CRUDY

[:post, :get, :put, :delete, :head]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(req_body = $stdin, env = ENV, opts = {}) ⇒ Controller

Main processing method of Controller.

The response body is set with the result of the specified action method if the result is a String and @body has not been set to a String. The action method is determined respectively by env[:action], REQUEST_METHOD in downcased form, or ‘get’ by default.

By the time the Controller.new is done running, it should have @status, @headers, and @body set. @status should be an Integer matching the http status code, @headers a string keyed hash of http headers, and @body to a string of the http response body.

Raises:

  • (NoMethodError)


553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
# File 'lib/maveric.rb', line 553

def initialize req_body=$stdin, env=ENV, opts={}
  ::Maveric.log.warn "Provided env has not been properly processed, results "+
    "may vary!" unless ([:maveric, :route, :params, :cookies]-env.keys).empty?
  ::Maveric.type_check :req_body, req_body, StringIO, IO
  ::Maveric.type_check :env, env, Hash
  ::Maveric.type_check :opts, opts, Hash

  @status, @headers = 200, {'Content-Type'=>'text/html'}
  @env, @in = env, req_body
  @cookies = @env[:cookies].dup

  action ||= @env[:route][:action] rescue nil
  action ||= @env['REQUEST_METHOD'].downcase rescue nil
  action ||= 'get'
  action = action.to_sym

  raise NoMethodError, [503, "#{action} not implemented.", nil, @env] if \
    REQUEST_METHODS.include? action and not respond_to? action

  self.class.before.select do |act|
    (act[:only].nil? or act[:only].include? action) and \
    (act[:exclude].nil? or not act[:exclude].include? action)
  end.each do |act|
    act[:do] ? act[:do][self] : __send__(act[:name], self)
  end

  @body = __send__ action

  self.class.after.select do |act|
    (act[:only].nil? or act[:only].include? action) and \
    (act[:exclude].nil? or not act[:exclude].include? action)
  end.each do |act|
    act[:do] ? act[:do][self] : __send__(act[:name], self)
  end

  ::Maveric.log.debug self # omg, masochistic.
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body.



591
592
593
# File 'lib/maveric.rb', line 591

def body
  @body
end

#headersObject (readonly)

Returns the value of attribute headers.



591
592
593
# File 'lib/maveric.rb', line 591

def headers
  @headers
end

#statusObject (readonly)

Returns the value of attribute status.



591
592
593
# File 'lib/maveric.rb', line 591

def status
  @status
end

Class Method Details

.add_route(r, o = {}) ⇒ Object

Add a route to the Controller.



468
469
470
471
472
# File 'lib/maveric.rb', line 468

def add_route r, o={}
  ::Maveric.type_check :r, r, String, ::Maveric::Route
  r = ::Maveric::Route.new r, o if r.is_a? String
  @routes << r
end

.after(act = {}, &block) ⇒ Object

If no argument is given, the array of actions is returned.

If a Symbol or String is given with no block, during Controller initialization after the action is called, the corresponding method is called with the Controller instance as an argument. If a block is given, the block is called with the controller instance as an argument instead.

If you are specifying other options, you must explicitly state :name => <chosen label> as an argument. Additional arguments include :only and :exclude, whose values should be a Symbol or an Array of such that correspond with actions that they should only run on or not run on.

NOTE: If you are referencing instance variables within the action, it is recommended that you create a method rather than a block.



530
531
532
533
534
535
536
537
538
# File 'lib/maveric.rb', line 530

def after act={}, &block
  ::Maveric.type_check :act, act, Hash, Symbol, String
  return @after if act.is_a? Hash and act.empty?
  act = {:name => act} unless act.is_a? Hash
  act[:do] = block
  act[:only]=[*act[:only]] if act.key? :only
  act[:exclude]=[*act[:exclude]] if act.key? :exclude
  @after << act
end

.before(act = {}, &block) ⇒ Object

If no argument is given, the array of actions is returned.

If a Symbol or String is given with no block, during Controller initialization before the action is called, the corresponding method is called with the Controller instance as an argument. If a block is given, the block is called with the controller instance as an argument instead.

If you are specifying other options, you must explicitly state :name => <chosen label> as an argument. Additional arguments include :only and :exclude, whose values should be a Symbol or an Array of such that correspond with actions that they should only run on or not run on.

NOTE: If you are referencing instance variables within the action, it is recommended that you create a method rather than a block.



503
504
505
506
507
508
509
510
511
# File 'lib/maveric.rb', line 503

def before act={}, &block
  ::Maveric.type_check :act, act, Hash, Symbol, String
  return @before if act.is_a? Hash and act.empty?
  act = {:name => act} unless act.is_a? Hash
  act[:do] = block
  act[:only]=[*act[:only]] if act.key? :only
  act[:exclude]=[*act[:exclude]] if act.key? :exclude
  @before << act
end

.clear_routesObject

Removes all currently set routes.



475
476
477
# File 'lib/maveric.rb', line 475

def clear_routes
  @routes.clear
end

.inherited(klass) ⇒ Object

Family is important.



450
451
452
453
454
455
456
457
# File 'lib/maveric.rb', line 450

def inherited klass
  parent = self
  klass.class_eval do
    @routes = []
    @before = parent.before.dup
    @after = parent.after.dup
  end
end

.routesObject

Returns a default Route based on the #nesting_path if no routes.



480
481
482
483
484
# File 'lib/maveric.rb', line 480

def routes
  @routes.empty? ?
    ::Maveric::Route.new(nesting_path) :
    @routes
end

.set_routes(r, o = {}) ⇒ Object

Removes currently set routes and adds the stated ones.



460
461
462
463
464
465
# File 'lib/maveric.rb', line 460

def set_routes r, o={}
  ::Maveric.type_check :r, r, String, Array
  clear_routes
  r = [r] unless r.is_a? Array
  r.flatten.map{|e| add_route e }
end

Instance Method Details

#cleanup_1_sessionsObject

Touches the session and includes it into the http headers.



68
69
70
71
# File 'lib/maveric/sessions.rb', line 68

def cleanup_1_sessions
  @env[:session].touch
  @headers['Set-Cookie'] = [@env[:session].to_s(@env)]
end

#to_httpObject

For quick and raw response outputting!



594
595
596
597
598
# File 'lib/maveric.rb', line 594

def to_http
  response = "Status: #{@status}" + ::Maveric::EOL # Status message? :/
  response << @headers.map{|k,v| "#{k}: #{v}" }*::Maveric::EOL
  response << ::Maveric::EOL*2 + @body
end