Class: HasFixtures::Sweatshop

Inherits:
Object
  • Object
show all
Defined in:
lib/has_fixtures/version.rb,
lib/has_fixtures/sweatshop.rb

Constant Summary collapse

VERSION =
"0.0.1"

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.model_mapObject

Returns the value of attribute model_map.



4
5
6
# File 'lib/has_fixtures/sweatshop.rb', line 4

def model_map
  @model_map
end

.record_mapObject

Returns the value of attribute record_map.



5
6
7
# File 'lib/has_fixtures/sweatshop.rb', line 5

def record_map
  @record_map
end

Class Method Details

.add(klass, name, &proc) ⇒ Object



11
12
13
# File 'lib/has_fixtures/sweatshop.rb', line 11

def self.add(klass, name, &proc)
  self.model_map[klass][name.to_sym] << proc
end

.attributes(klass, name) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/has_fixtures/sweatshop.rb', line 37

def self.attributes(klass, name)
  proc = model_map[klass][name.to_sym].pick

  if !proc.nil?
    proc.call
  elsif klass.superclass.include?(HasFixtures::Base)
    attributes(klass.superclass, name)
  else
    raise "#{name} fixture was not found"
  end
end

.create(klass, name, attributes = {}) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/has_fixtures/sweatshop.rb', line 20

def self.create(klass, name, attributes = {})
  begin
    record(klass, name, klass.create(attributes(klass, name).merge(attributes)))
  rescue StandardError => e
    retry if e.message =~ /^column \w+ is not unique$/
    raise e
  end
end

.load_all(options = {}) ⇒ Object

TODO: spec



49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/has_fixtures/sweatshop.rb', line 49

def self.load_all(options = {}) # TODO: spec
  HasFixtures::Sweatshop.model_map.each do |klass, keys|
    keys.each do |key, procs|
      procs.each do |p|
        values = p.call
        $stderr.puts ">> #{klass}: #{key}" if options[:verbose]
        values.each do |k, v|
          $stderr.puts "  #{k+(' '*(30-k.size).abs)}#{v}" if options[:verbose]
        end
        klass.create(values)
      end
    end
  end
end

.make(klass, name, attributes = {}) ⇒ Object



29
30
31
# File 'lib/has_fixtures/sweatshop.rb', line 29

def self.make(klass, name, attributes = {})
  record(klass, name, klass.new(attributes(klass, name).merge(attributes)))
end

.pick(klass, name) ⇒ Object



33
34
35
# File 'lib/has_fixtures/sweatshop.rb', line 33

def self.pick(klass, name)
  self.record_map[klass][name.to_sym].pick || raise(NoFixturesExist, "no #{name} context fixtures have been generated for the #{klass} class")
end

.record(klass, name, instance) ⇒ Object



15
16
17
18
# File 'lib/has_fixtures/sweatshop.rb', line 15

def self.record(klass, name, instance)
  self.record_map[klass][name.to_sym] << instance
  instance
end