Class: Transfer::Transferer

Inherits:
Object
  • Object
show all
Defined in:
lib/transfer/transferer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dataset, klass, &block) ⇒ Transferer

Returns a new instance of Transferer.



4
5
6
7
8
# File 'lib/transfer/transferer.rb', line 4

def initialize dataset, klass, &block
  @dataset = dataset
  @klass = klass
  block.arity == 1 ? yield(self) : instance_eval(&block) if block_given?
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(symbol, *args, &block) ⇒ Object



29
30
31
# File 'lib/transfer/transferer.rb', line 29

def method_missing symbol, *args, &block
  add_column symbol, block_given? ? block : args[0]
end

Instance Attribute Details

#datasetObject (readonly)

Returns the value of attribute dataset.



2
3
4
# File 'lib/transfer/transferer.rb', line 2

def dataset
  @dataset
end

#klassObject (readonly)

Returns the value of attribute klass.



2
3
4
# File 'lib/transfer/transferer.rb', line 2

def klass
  @klass
end

Instance Method Details

#after_save(&block) ⇒ Object



54
55
56
# File 'lib/transfer/transferer.rb', line 54

def after_save &block
  callbacks[:after_save] = block
end

#before_save(&block) ⇒ Object



50
51
52
# File 'lib/transfer/transferer.rb', line 50

def before_save &block
  callbacks[:before_save] = block
end

#build_attributes(source) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/transfer/transferer.rb', line 14

def build_attributes source
  attrs = {}
  columns.each do |name, value|
    attrs[name] = case value
      when Proc
        value.call source
      when Symbol
        source[value]
      else
        value
      end
  end
  attrs
end

#callbacksObject



46
47
48
# File 'lib/transfer/transferer.rb', line 46

def callbacks
  @callbacks ||= {}
end

#columnsObject



10
11
12
# File 'lib/transfer/transferer.rb', line 10

def columns
  @columns ||= dataset.columns.each_with_object({}){|i,hash| hash[i]=i if generator.column_present? i }
end

#generatorObject

end



62
63
64
# File 'lib/transfer/transferer.rb', line 62

def generator
  @generator ||= GENERATORS.detect{|g| g.supports? klass}.new klass
end

#process(options = {}) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/transfer/transferer.rb', line 33

def process options = {}
  generator.before
  options[:before].call(klass, dataset) if options[:before]
  generator.transaction do
    dataset.each do |row|
      attributes = build_attributes row
      generator.create attributes, row, options, callbacks
    end
  end
  options[:after].call(klass, dataset) if options[:after]
  generator.after
end