Class: EmeraldODM::AttrInitializer
- Inherits:
-
Object
- Object
- EmeraldODM::AttrInitializer
- Defined in:
- lib/emerald_odm.rb
Direct Known Subclasses
Instance Attribute Summary collapse
-
#_document ⇒ Object
readonly
Returns the value of attribute _document.
Class Method Summary collapse
Instance Method Summary collapse
- #empty? ⇒ Boolean
-
#initialize(document) ⇒ AttrInitializer
constructor
A new instance of AttrInitializer.
- #nil? ⇒ Boolean
- #to_h ⇒ Object
Constructor Details
#initialize(document) ⇒ AttrInitializer
Returns a new instance of AttrInitializer.
31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/emerald_odm.rb', line 31 def initialize(document) if document.instance_of?(Hash) document = BSON::Document.new(document) elsif document.nil? document = BSON::Document.new end self.class.fields.each do |field| document_value = document[field] send("#{field}=", document_value) end instance_variable_set('@_document', document) end |
Instance Attribute Details
#_document ⇒ Object (readonly)
Returns the value of attribute _document.
28 29 30 |
# File 'lib/emerald_odm.rb', line 28 def _document @_document end |
Class Method Details
.array_to_h(array) ⇒ Object
65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/emerald_odm.rb', line 65 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 |
.fields ⇒ Array
45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/emerald_odm.rb', line 45 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
#empty? ⇒ Boolean
61 62 63 |
# File 'lib/emerald_odm.rb', line 61 def empty? _document.nil? || _document.empty? end |
#nil? ⇒ Boolean
57 58 59 |
# File 'lib/emerald_odm.rb', line 57 def nil? _document.nil? || _document.empty? end |
#to_h ⇒ Object
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
# File 'lib/emerald_odm.rb', line 77 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 |