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_strings_to_symbols
  id_tags = id_tags.map(&:to_sym)
  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

#indifferent_hash(field_name, method_name) ⇒ Object



54
55
56
57
58
59
60
61
62
63
# File 'lib/libis/workflow/mongoid/base.rb', line 54

def indifferent_hash(field_name, method_name)
  define_method method_name do
    MapWithIndifferentAccess::Map.new(self.read_attribute(field_name))
  end

  define_method "#{method_name}=" do |value|
    self.write_attribute(field_name, value)
    self.send(method_name)
  end
end