Class: CreateThroughRepositoryStrategy::Create

Inherits:
Object
  • Object
show all
Defined in:
lib/minimapper/factory_girl.rb

Instance Method Summary collapse

Instance Method Details

#associated_entity_namesObject



49
50
51
52
53
# File 'lib/minimapper/factory_girl.rb', line 49

def associated_entity_names
  entity.class.column_names.find_all { |name| name[-3..-1] == '_id' }.map do |belongs_to_id|
    belongs_to_id[0...-3]
  end
end

#createObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/minimapper/factory_girl.rb', line 14

def create
  entity_class = entity.class
  mapper_name = entity_class.name.underscore.pluralize

  # Recursively creates all dependencies of this entity before
  # going on to the the entity itself. This is here so that we can do
  # "customer { FactoryGirl.build(:customer) }" in factories.
  create_dependencies

  if entity.persisted?
    entity
  elsif mapper_with_name(mapper_name).create(entity)
    entity
  else
    errors = entity.errors.full_messages.join(", ")
    raise "Can't create invalid record: #{errors}"
  end
end

#create_dependenciesObject



38
39
40
41
42
43
44
45
46
47
# File 'lib/minimapper/factory_girl.rb', line 38

def create_dependencies
  associated_entity_names.each do |name|
    associated_entity = entity.public_send(name)

    if associated_entity
      dependency_entity = self.class.new(associated_entity).create
      entity.public_send("#{name}=", dependency_entity)
    end
  end
end

#mapper_with_name(name) ⇒ Object

Override this if you want to access the mappers some other way.



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

def mapper_with_name(name)
  Repository.public_send(name)
end