Module: Libis::Workflow::Mongoid::Base::ClassMethods

Defined in:
lib/libis/workflow/mongoid/base.rb

Instance Method Summary collapse

Instance Method Details

#create_from_hash(hash, id_tags, &block) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/libis/workflow/mongoid/base.rb', line 36

def create_from_hash(hash, id_tags, &block)
  hash = hash.key_symbols_to_strings(recursive: true)
  id_tags = id_tags.map(&:to_s)
  return nil unless id_tags.empty? || id_tags.any? { |k| hash.include?(k) }
  tags = id_tags.inject({}) do |h, k|
    v = hash.delete(k)
    h[k] = v if v
    h
  end
  item = tags.empty? ? self.new : self.find_or_initialize_by(tags)
  block.call(item, hash) if block unless hash.empty?
  item.assign_attributes(hash)
  unless self.embedded?
    item.save!
  end
  item
end

#from_hash(hash) ⇒ Object



32
33
34
# File 'lib/libis/workflow/mongoid/base.rb', line 32

def from_hash(hash)
  self.create_from_hash(hash.cleanup, [:name])
end