Class: DataAccessorModule

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

Instance Method Summary collapse

Constructor Details

#initialize(mapping) ⇒ DataAccessorModule

Returns a new instance of DataAccessorModule.



2
3
4
5
# File 'lib/csv_madness/data_accessor_module.rb', line 2

def initialize( mapping )
  @column_accessors = []
  remap_accessors( mapping )
end

Instance Method Details

#install_column_accessors(column, index) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/csv_madness/data_accessor_module.rb', line 7

def install_column_accessors( column, index )
  @column_accessors << column
  eval <<-EOF
    self.send( :define_method, :#{column} ) do
      self.csv_data[#{index}]
    end
    
    self.send( :define_method, :#{column}= ) do |val|
      self.csv_data[#{index}] = val
    end
  EOF
end

#remap_accessors(mapping) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/csv_madness/data_accessor_module.rb', line 35

def remap_accessors( mapping )
  remove_all_column_accessors
  
  @mapping = mapping
  
  for column, index in @mapping
    install_column_accessors( column, index )
  end
end

#remove_all_column_accessorsObject



25
26
27
28
29
30
31
32
33
# File 'lib/csv_madness/data_accessor_module.rb', line 25

def remove_all_column_accessors
  @column_accessors ||= []    
  
  for sym in @column_accessors
    remove_column_accessors( sym )
  end
  
  @column_accessors = []    
end

#remove_column_accessors(column) ⇒ Object



20
21
22
23
# File 'lib/csv_madness/data_accessor_module.rb', line 20

def remove_column_accessors( column )
  self.send( :remove_method, column )
  self.send( :remove_method, :"#{column}=" )
end