Module: Ruport::Controller::Hooks

Included in:
Data::Group, Data::Grouping, Data::Record, Data::Table
Defined in:
lib/ruport/controller.rb

Overview

This module provides hooks into Ruport’s formatting system. It is used to implement the as() method for all of Ruport’s data structures, as well as the renders_with and renders_as_* helpers.

You can actually use this with any data structure, it will look for a renderable_data(format) method to pass to the controller you specify, but if that is not defined, it will pass self.

Examples:

# Render Arrays with Ruport's Row Controller
class Array
  include Ruport::Controller::Hooks
  renders_as_row
end

# >> [1,2,3].as(:csv) 
# => "1,2,3\n" 

# Render Hashes with Ruport's Row Controller
class Hash
   include Ruport::Controller::Hooks
   renders_as_row
   attr_accessor :column_order
   def renderable_data(format)
     column_order.map { |c| self[c] }
   end
end

# >> a = { :a => 1, :b => 2, :c => 3 }
# >> a.column_order = [:b,:a,:c]
# >> a.as(:csv)
# => "2,1,3\n"

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object

:nodoc:



154
155
156
# File 'lib/ruport/controller.rb', line 154

def self.included(base) #:nodoc:
  base.extend(ClassMethods)
end

Instance Method Details

#as(format, options = {}) ⇒ Object

Uses the Controller specified by renders_with to generate formatted output. Passes the return value of the renderable_data(format) method if the method is defined, otherwise passes self as :data

The remaining options are converted to a Controller::Options object and are accessible in both the controller and formatter.

Example:

  table.as(:csv, :show_table_headers => false)


168
169
170
171
172
173
174
175
# File 'lib/ruport/controller.rb', line 168

def as(format, options = {})
  raise ControllerNotSetError unless self.class.controller
  raise UnknownFormatError unless self.class.controller.formats.include?(format)
  self.class.controller.render(format, self.class.rendering_options.merge(options)) do |rend|
      rend.data = respond_to?(:renderable_data) ? renderable_data(format) : self
      yield(rend) if block_given?
  end
end

#save_as(file, options = {}) ⇒ Object



177
178
179
180
181
# File 'lib/ruport/controller.rb', line 177

def save_as(file,options={})
  file =~ /.*\.(.*)/    
  format = $1
  as(format.to_sym, options.merge(:file => file))        
end