Module: ActiverecordToPoro::MetadataEnabledAr::ClassMethods

Defined in:
lib/activerecord_to_poro/metadata_enabled_ar.rb

Instance Method Summary collapse

Instance Method Details

#_apply_change_set_to_record(attached_record, changes) ⇒ Object



68
69
70
71
72
# File 'lib/activerecord_to_poro/metadata_enabled_ar.rb', line 68

def _apply_change_set_to_record(attached_record, changes)
  changes.each_pair do |attr_name, (_, new_value)|
    attached_record.public_send("#{attr_name}=", new_value)
  end
end

#_as_scope(attr) ⇒ Object



74
75
76
# File 'lib/activerecord_to_poro/metadata_enabled_ar.rb', line 74

def _as_scope(attr)
  attr.empty? ? none : where(attr)
end

#_extract_metadata!(attrs) ⇒ Object



78
79
80
81
# File 'lib/activerecord_to_poro/metadata_enabled_ar.rb', line 78

def _extract_metadata!(attrs)
   = (attrs || {}).delete(:_set_metadata_to_ar){ |*| Metadata.new }
  .for_ar_class(self.name)
end

#_from_attrs_with_metadata(attrs = {}, pre_created_object = nil) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/activerecord_to_poro/metadata_enabled_ar.rb', line 34

def (attrs={}, pre_created_object= nil)
  record_by_primary_key = _record_from_metadata!(attrs)

  record = pre_created_object || record_by_primary_key || new

  record.tap do |new_obj|

    new_obj.attributes = attrs || {}

    _patch_has_many_members(attrs, new_obj) unless new_obj.new_record?
  end

end

#_has_many_attr_names(obj_or_class) ⇒ Object



63
64
65
66
# File 'lib/activerecord_to_poro/metadata_enabled_ar.rb', line 63

def _has_many_attr_names(obj_or_class)
  class_to_check = obj_or_class.respond_to?(:reflect_on_all_associations) ? obj_or_class : obj_or_class.class
  class_to_check.reflect_on_all_associations(:has_many).map(&:name)
end

#_patch_has_many_members(attrs, new_obj) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/activerecord_to_poro/metadata_enabled_ar.rb', line 48

def _patch_has_many_members(attrs, new_obj)
  has_many_attrs = attrs.slice(* _has_many_attr_names(new_obj))

  has_many_attrs.each_pair do |name, updated_records|

    new_obj.public_send(name).each do |attached_record|
      record_with_updated_values = updated_records.find { |r| r == attached_record }
      next unless record_with_updated_values

      _apply_change_set_to_record(attached_record, record_with_updated_values.changes)
    end

  end
end

#_record_from_metadata!(attrs) ⇒ Object



83
84
85
86
87
88
89
90
91
# File 'lib/activerecord_to_poro/metadata_enabled_ar.rb', line 83

def _record_from_metadata!(attrs)
   = _extract_metadata!(attrs)

  if respond_to?(:query_from_cache) && query_from_cache(.as_scope_hash)
    query_from_cache(.as_scope_hash)
  else
    _as_scope(.as_scope_hash).first
  end
end