Module: EmbedUtils

Defined in:
lib/mongoid_fixtures/embed_utils.rb

Class Method Summary collapse

Class Method Details

.create_embedded_instance(clazz, hash, instance) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
# File 'lib/mongoid_fixtures/embed_utils.rb', line 2

def self.create_embedded_instance(clazz, hash, instance)
  embed = clazz.new

  unless hash.is_a? Hash
    raise("#{hash} was supposed to be a collection of #{embed}. You have configured #{clazz} objects to be embedded instances of #{instance}.\nPlease store these objects within the #{instance} yml. Refer to the documentation for examples.")
  end

  hash.each do |key, value|
    embed.send("#{key}=", value)
  end
  embed.send("#{find_embed_parent_class(embed)}=", instance)
  embed
end

.find_embed_parent_class(embed) ⇒ Object



16
17
18
19
20
21
22
23
24
25
# File 'lib/mongoid_fixtures/embed_utils.rb', line 16

def self.find_embed_parent_class(embed)
  relations = embed.relations

  relations.each do |name, relation|
    if relation.relation.eql? Mongoid::Relations::Embedded::In
      return name
    end
  end
  raise 'Unable to find parent class'
end

.insert_embedded_ids(instance) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/mongoid_fixtures/embed_utils.rb', line 27

def self.insert_embedded_ids(instance)
  attributes = instance.attributes.select { |key, _| !key.to_s.eql?('_id') }

  attributes.each do |key, value|
    if attributes[key].is_a? Hash
      unless instance.send(key)._id.nil?
        attributes[key]['_id'] = instance.send(key)._id
      end
    else
      attributes[key] = value
    end
  end
  attributes
end