Class: CsvMadness::Builder

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

Instance Method Summary collapse

Constructor Details

#initialize {|_self| ... } ⇒ Builder

Returns a new instance of Builder.

Yields:

  • (_self)

Yield Parameters:



3
4
5
6
7
8
9
# File 'lib/csv_madness/builder.rb', line 3

def initialize( &block )
  @columns = {}
  @column_syms = []
  @module = Module.new   # for extending
  self.extend( @module )
  yield self
end

Instance Method Details

#build(objects, opts = { :on_error => :print }) ⇒ Object

Three :on_error values:

:print  => Put an error message in the cell instead of a value
:raise  => Raise the error, halting the process
:ignore => Hand back an empty cell

Although ideally it should be configurable by column…



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/csv_madness/builder.rb', line 30

def build( objects, opts = { :on_error => :print } )
  spreadsheet = CsvMadness::Sheet.new( @column_syms )

  for object in objects
    STDOUT << "."
    record = {}
    for sym in @column_syms
      record[sym] = build_cell( object, sym, opts )
    end

    spreadsheet.add_record( record )  # hash form
  end

  spreadsheet
end

#build_cell(object, sym, opts = { :on_error => :print }) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/csv_madness/builder.rb', line 46

def build_cell( object, sym, opts = { :on_error => :print } )
  column = @columns[sym]

  case column
  when String
    build_cell_by_pathstring( object, column, opts )
  when Proc
    build_cell_by_proc( object, column, opts )
  else
    "no idea what to do"
  end
end

#column(sym, method_path = nil, &block) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/csv_madness/builder.rb', line 11

def column( sym, method_path = nil, &block )
  warn( "#{sym} already defined. Overwriting." ) if @column_syms.include?( sym )
  
  @column_syms << sym
  @columns[sym] = if block_given?
                    block
                  elsif method_path
                    method_path
                  else
                    Proc.new(&sym)
                  end
end

#def(method_name, &block) ⇒ Object



59
60
61
# File 'lib/csv_madness/builder.rb', line 59

def def( method_name, &block )
  @module.send( :define_method, method_name, &block )
end