Class: LetMeSendEmail::Models::Model
- Inherits:
-
Object
- Object
- LetMeSendEmail::Models::Model
- Includes:
- Enumerable
- Defined in:
- lib/letmesendemail/models.rb
Overview
Application-friendly representation of an API response.
Nested hashes and arrays are recursively wrapped. Use #to_h for a defensive plain-data copy suitable for database persistence.
Instance Method Summary collapse
-
#[](key) ⇒ Object?
Wrapped field value.
-
#as_json ⇒ Hash
Rails-compatible JSON representation.
-
#each {|key, value| ... } ⇒ Enumerator, self
Iterates through response fields.
-
#fetch(key, *defaults) ⇒ Object
Wrapped field value.
-
#initialize(attributes) ⇒ Model
constructor
A new instance of Model.
- #inspect ⇒ String
-
#key?(key) ⇒ Boolean
Whether the field exists.
-
#to_h ⇒ Hash
Recursive defensive plain-data copy.
-
#to_json(*args) ⇒ String
JSON document.
Constructor Details
#initialize(attributes) ⇒ Model
Returns a new instance of Model.
16 17 18 19 20 21 22 |
# File 'lib/letmesendemail/models.rb', line 16 def initialize(attributes) raise ArgumentError, 'attributes must be a Hash' unless attributes.is_a?(Hash) @attributes = attributes.each_with_object({}) do |(key, value), result| result[key.to_s.dup.freeze] = Models.wrap(value) end.freeze end |
Instance Method Details
#[](key) ⇒ Object?
Returns wrapped field value.
26 27 28 |
# File 'lib/letmesendemail/models.rb', line 26 def [](key) @attributes[key.to_s] end |
#as_json ⇒ Hash
Rails-compatible JSON representation.
59 60 61 |
# File 'lib/letmesendemail/models.rb', line 59 def as_json(*) to_h end |
#each {|key, value| ... } ⇒ Enumerator, self
Iterates through response fields.
46 47 48 49 50 |
# File 'lib/letmesendemail/models.rb', line 46 def each(&block) return enum_for(:each) unless block @attributes.each(&block) end |
#fetch(key, *defaults) ⇒ Object
Returns wrapped field value.
32 33 34 |
# File 'lib/letmesendemail/models.rb', line 32 def fetch(key, *defaults, &) @attributes.fetch(key.to_s, *defaults, &) end |
#inspect ⇒ String
69 70 71 |
# File 'lib/letmesendemail/models.rb', line 69 def inspect "#<#{self.class.name} #{@attributes.inspect}>" end |
#key?(key) ⇒ Boolean
Returns whether the field exists.
38 39 40 |
# File 'lib/letmesendemail/models.rb', line 38 def key?(key) @attributes.key?(key.to_s) end |
#to_h ⇒ Hash
Returns recursive defensive plain-data copy.
53 54 55 |
# File 'lib/letmesendemail/models.rb', line 53 def to_h Models.unwrap(@attributes) end |
#to_json(*args) ⇒ String
Returns JSON document.
64 65 66 |
# File 'lib/letmesendemail/models.rb', line 64 def to_json(*args) to_h.to_json(*args) end |