Class: Findable::Seed

Inherits:
Object
  • Object
show all
Defined in:
lib/findable/seed.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, seed_dir) ⇒ Seed

Returns a new instance of Seed.



5
6
7
8
# File 'lib/findable/seed.rb', line 5

def initialize(path, seed_dir)
  @_seed_dir = seed_dir
  self.full_path = path
end

Instance Attribute Details

#extObject (readonly)

Returns the value of attribute ext.



3
4
5
# File 'lib/findable/seed.rb', line 3

def ext
  @ext
end

#full_pathObject

Returns the value of attribute full_path.



3
4
5
# File 'lib/findable/seed.rb', line 3

def full_path
  @full_path
end

#namespacedObject (readonly)

Returns the value of attribute namespaced.



3
4
5
# File 'lib/findable/seed.rb', line 3

def namespaced
  @namespaced
end

Class Method Details

.patterns(seed_dir) ⇒ Object



53
54
55
56
57
# File 'lib/findable/seed.rb', line 53

def patterns(seed_dir)
  %w(yml).map {|format|
    Rails.root.join("#{seed_dir}/**/*.#{format}").to_s
  }
end

.target_files(seed_dir, tables = nil) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/findable/seed.rb', line 45

def target_files(seed_dir, tables = nil)
  Dir.glob(patterns(seed_dir)).map {|full_path|
    Seed.new(full_path, seed_dir)
  }.select {|seed|
    tables ? tables.include?(seed.base_name) : true
  }
end

Instance Method Details

#base_nameObject



17
18
19
# File 'lib/findable/seed.rb', line 17

def base_name
  @_base ||= @namespaced.sub(@ext, "")
end

#bootstrap!Object



36
37
38
39
40
41
42
# File 'lib/findable/seed.rb', line 36

def bootstrap!
  model.transaction do
    model.delete_all
    records = load_file.map {|data| model.new(data) }
    model.import records
  end
end

#load_fileObject



27
28
29
30
31
32
33
34
# File 'lib/findable/seed.rb', line 27

def load_file
  case @ext
  when ".yml"
    YAML.load_file(@full_path).values
  else
    raise UnexpectedFormat
  end
end

#modelObject



21
22
23
24
25
# File 'lib/findable/seed.rb', line 21

def model
  base_name.split("/").reverse.map.with_index {|n,i|
    i.zero? ? n.singularize : n
  }.reverse.map(&:camelize).join("::").constantize
end