Class: AmberODM::AttrInitializer

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

Direct Known Subclasses

Document

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(document) ⇒ AttrInitializer

Returns a new instance of AttrInitializer.



30
31
32
33
34
35
36
# File 'lib/amber_odm.rb', line 30

def initialize(document)
  self.class.fields.each do |field|
    document_value = document&.dig(field).dup
    send("#{field}=", document_value) unless document_value.nil?
  end
  instance_variable_set('@document', document)
end

Instance Attribute Details

#_documentObject (readonly)

Returns the value of attribute _document.



28
29
30
# File 'lib/amber_odm.rb', line 28

def _document
  @_document
end

Class Method Details

.array_to_h(array) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/amber_odm.rb', line 55

def self.array_to_h(array)
  array.map do |item|
    if item.is_a?(AttrInitializer)
      item.to_h
    elsif item.is_a?(Array)
      array_to_h(item)
    else
      item
    end
  end
end

.fieldsArray

Returns:

  • (Array)


39
40
41
42
43
44
45
46
47
48
49
# File 'lib/amber_odm.rb', line 39

def self.fields
  public_instance_methods = self.public_instance_methods(false).grep(/=$/)
  rejected_attr_names = %w[document]
  fields = []
  public_instance_methods.each do |attr|
    attr_name = attr.to_s.gsub('=', '')
    next if rejected_attr_names.include?(attr_name)
    fields << attr_name
  end
  fields
end

Instance Method Details

#nil?Boolean

Returns:

  • (Boolean)


51
52
53
# File 'lib/amber_odm.rb', line 51

def nil?
  _document.nil? || _document.empty?
end

#to_hObject



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/amber_odm.rb', line 67

def to_h
  hash = {}
  known_fields = self.class.fields
  unknown_fields = _document.keys - known_fields
  unknown_fields.reject! { |field| field.start_with?('_') }
  known_fields.each do |field|
    value = send(field)
    if value.is_a?(AttrInitializer)
      hash[field] = value.to_h
    elsif value.is_a?(Array)
      hash[field] = self.class.array_to_h(value)
    else
      hash[field] = value
    end
  end
  unknown_fields.each do |field|
    value = _document[field]
    hash[field] = value
  end

  hash
end