Module: NRSER::Props::InstanceMethods
- Defined in:
- lib/nrser/props/instance_methods.rb
Overview
Instance methods to mix in to classes that include NRSER::Props.
Instance Method Summary collapse
- #dup ⇒ Object
- #merge(other, &block) ⇒ Object
-
#to_data(only_own: false, only_primary: false, add_class: true, class_key: NRSER::Props::DEFAULT_CLASS_KEY, compact: true) ⇒ Hash<String, *>
Create a “data” representation suitable for transport, storage, etc.
-
#to_h(only_own: false, only_primary: false, compact: true) ⇒ Hash<Symbol, Object>
Create a new hash with property names mapped to values.
-
#to_json(*args) ⇒ String
Get a JSON String encoding the instance’s data.
-
#to_yaml(*args) ⇒ String
Get a YAML String encoding the instance’s data.
Instance Method Details
#dup ⇒ Object
82 83 84 85 |
# File 'lib/nrser/props/instance_methods.rb', line 82 def dup self.class.new \ self.to_h( only_primary: true ) end |
#merge(other, &block) ⇒ Object
75 76 77 78 79 |
# File 'lib/nrser/props/instance_methods.rb', line 75 def merge other, &block self.class.new \ self.to_h( only_primary: true ). merge( other.symbolize_keys, &block ) end |
#to_data(only_own: false, only_primary: false, add_class: true, class_key: NRSER::Props::DEFAULT_CLASS_KEY, compact: true) ⇒ Hash<String, *>
Create a “data” representation suitable for transport, storage, etc.
The result is meant to consist of only basic data types and structures - strings, numbers, arrays, hashes, datetimes, etc… though it depends on any custom objects it encounters correctly responding to ‘#to_data` for this to happen (as is implemented from classes that mix in Props here).
Prop names are converted to strings (from symbols) since though YAML supports symbol values, they have poor portability across languages, and they mean the same thing in this situation.
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 |
# File 'lib/nrser/props/instance_methods.rb', line 137 def to_data only_own: false, only_primary: false, add_class: true, class_key: NRSER::Props::DEFAULT_CLASS_KEY, compact: true hash = self.class.props(only_own: only_own, only_primary: only_primary). map { |name, prop| [name.to_s, prop.to_data(self)] }. to_h hash.compact! if compact hash[class_key] = self.class.safe_name if add_class hash end |
#to_h(only_own: false, only_primary: false, compact: true) ⇒ Hash<Symbol, Object>
Create a new hash with property names mapped to values.
99 100 101 102 103 104 105 106 107 |
# File 'lib/nrser/props/instance_methods.rb', line 99 def to_h only_own: false, only_primary: false, compact: true hash = self.class. props(only_own: only_own, only_primary: only_primary). transform_values { |prop| prop.get self } hash.compact! if compact hash end |