Module: AttributeKit::JSONSerializableHash
- Defined in:
- lib/attribute-kit/json_serializable_hash.rb
Overview
JSONSerializableHash adds a set of methods to manage serialization and deserialization of hashes and Hash decendants in a consistent manner. By default, the methods symbolize the keys when they are deserialized, which greatly improves performance and also provides consistency in how keys appear both in JSON and in the hash.
Instance Method Summary collapse
-
#from_json(json, opts = {}) ⇒ Hash
Deserializes hash contents from a JSON string, replacing the contents of the hash if they already exist.
-
#get_json(key, opts = {}) ⇒ String
Serializes a single key-value pair from the hash contents into a JSON string.
-
#store_json(json, opts = {}) ⇒ Hash
Deserializes hash contents from a JSON string, merging the contents with any contents of the hash that already exist.
-
#to_json(opts = {}) ⇒ String
Serializes the entire hash contents into a JSON string.
Instance Method Details
#from_json(json, opts = {}) ⇒ Hash
Deserializes hash contents from a JSON string, replacing the contents of the hash if they already exist
79 80 81 82 83 84 85 |
# File 'lib/attribute-kit/json_serializable_hash.rb', line 79 def from_json(json, opts = {}) defaults = { :symbolize_keys => true } opts.merge!(defaults){ |key, param, default| param } self.replace(JSON.parse(json, opts)) end |
#get_json(key, opts = {}) ⇒ String
Serializes a single key-value pair from the hash contents into a JSON string.
91 92 93 |
# File 'lib/attribute-kit/json_serializable_hash.rb', line 91 def get_json(key, opts = {}) JSON.generate({key => self[key]}, opts) end |
#store_json(json, opts = {}) ⇒ Hash
Deserializes hash contents from a JSON string, merging the contents with any contents of the hash that already exist
99 100 101 102 103 104 105 |
# File 'lib/attribute-kit/json_serializable_hash.rb', line 99 def store_json(json, opts = {}) defaults = { :symbolize_keys => true } opts.merge!(defaults){ |key, param, default| param } self.update(JSON.parse(json, opts)) end |
#to_json(opts = {}) ⇒ String
Serializes the entire hash contents into a JSON string.
71 72 73 |
# File 'lib/attribute-kit/json_serializable_hash.rb', line 71 def to_json(opts = {}) JSON.generate(self, opts) end |