Module: SimpleImporter

Included in:
Importer
Defined in:
lib/simple_importer.rb

Defined Under Namespace

Classes: Importer

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.[](name) ⇒ Object



63
64
65
# File 'lib/simple_importer.rb', line 63

def self.[](name)
  importers.select{|i| i.name == name}.first
end

.config_methsObject



51
52
53
# File 'lib/simple_importer.rb', line 51

def self.config_meths
  csv_config_meths + [:file, :callbacks, :desc]
end

.csv_config_methsObject



47
48
49
# File 'lib/simple_importer.rb', line 47

def self.csv_config_meths
  CSV::DEFAULT_OPTIONS.keys
end

.find_importersObject



38
39
40
41
42
43
44
45
# File 'lib/simple_importer.rb', line 38

def self.find_importers
  importer_paths.each do |path| 
    Dir[File.join(path, '*.rb')].each do |file|
      coedz = File.open(file).read
      SimpleImporter.class_eval(coedz)
    end
  end
end

.importer(name, &block) ⇒ Object



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

def self.importer(name, &block)
  importers << Importer.new(name, &block)
end

.importer_pathsObject



34
35
36
# File 'lib/simple_importer.rb', line 34

def self.importer_paths
  %w{importers app/importers lib/importers}
end

.importersObject



55
56
57
# File 'lib/simple_importer.rb', line 55

def self.importers
  @importers ||= []
end

.included(base) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/simple_importer.rb', line 10

def self.included(base)
  config_meths.each do |meth|
    base.class_eval <<-METH
      def #{meth}(val = nil)
        config[:#{meth}] = val unless val.nil?
        config[:#{meth}]
      end
    METH
  end

  [:before, :foreach, :foreach_file].each do |meth|
    base.class_eval <<-METH
      def #{meth}(&block)
        config[:#{meth}] = block if block_given?
        config[:#{meth}]
      end
    METH
  end
  
  base.class_eval do
    attr_accessor :name
  end
end

Instance Method Details

#configObject



67
68
69
70
71
72
73
74
75
# File 'lib/simple_importer.rb', line 67

def config
  @config ||= {
    :callbacks => true,
    :headers => true,
    :header_converters => :symbol,
    :converters => :all,
    :desc => 'a simple_import importer'
  }
end

#csv_configObject



77
78
79
80
81
82
83
84
# File 'lib/simple_importer.rb', line 77

def csv_config
  ret = {}
  config.each do |k, v|
    ret[k] = config[k] if SimpleImporter.csv_config_meths.include?(k)
  end
  ret
  # config.select{|k,v| SimpleImporter.csv_config_meths.include?(k)}
end

#runObject



86
87
88
89
90
91
92
# File 'lib/simple_importer.rb', line 86

def run
  run_callbacks
  [file].flatten.each do |f|
    foreach_file.call(f) if foreach_file
    CSV.foreach(f, csv_config, &foreach) if foreach
  end
end

#run_callbacksObject



94
95
96
# File 'lib/simple_importer.rb', line 94

def run_callbacks
  self.before.call if callbacks && before
end