Module: Waves::Controllers::Mixin

Includes:
ResponseMixin
Defined in:
lib/controllers/mixin.rb

Overview

This mixin provides some handy methods for Waves controllers. You will probably want to include it in any controllers you define for your application. The default controllers generated using the wave command already do this.

Basically, what the mixin does is adapt the class so that it can be used within mappings (see Waves::Mapping); add some simple reflection to allow controller methods to be written generically (i.e., without reference to a specific model); and provide parameter destructuring for the request parameters.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ResponseMixin

#controllers, #domain, #log, #models, #not_found, #path, #redirect, #response, #session, #url, #views

Instance Attribute Details

#requestObject (readonly)

Returns the value of attribute request.



91
92
93
# File 'lib/controllers/mixin.rb', line 91

def request
  @request
end

Class Method Details

.included(c) ⇒ Object

When you include this Mixin, a process class method is added to your class, which accepts a request object and a block. The request object is used to initialize the controller and the block is evaluated using instance_eval. This allows the controller to be used within a mapping file.



100
101
102
103
104
# File 'lib/controllers/mixin.rb', line 100

def self.included( c )
  def c.process( request, &block )
    self.new( request ).instance_eval( &block )
  end
end

Instance Method Details

#initialize(request) ⇒ Object



106
# File 'lib/controllers/mixin.rb', line 106

def initialize( request ); @request = request; end

#modelObject

This uses the model_name method to attempt to identify the model corresponding to this controller. This allows you to write generic controller methods such as:

model.find( name )

to find an instance of a given model. Again, the plurality of the controller and model must be the same for this to work.



129
# File 'lib/controllers/mixin.rb', line 129

def model; Waves.application.models[ model_name.intern ]; end

#model_nameObject

You can access the name of the model related to this controller using this method. It simply takes the basename of the module and converts it to snake case, so if the model uses a different plurality, this won’t, in fact, be the model name.



120
# File 'lib/controllers/mixin.rb', line 120

def model_name; self.class.basename.snake_case; end

#paramsObject

The params variable is taken from the request object and “destructured”, so that a parameter named ‘blog.title’ becomes:

params['blog']['title']

If you want to access the original parameters object, you can still do so using request.parameters instead of simply params.



115
# File 'lib/controllers/mixin.rb', line 115

def params; @params ||= destructure(request.params); end