Module: Sequel::Plugins::JsonSerializer::ClassMethods
- Defined in:
- lib/sequel/plugins/json_serializer.rb
Instance Attribute Summary collapse
-
#json_serializer_opts ⇒ Object
readonly
The default opts to use when serializing model objects to JSON.
Instance Method Summary collapse
-
#inherited(subclass) ⇒ Object
Copy the current model object’s default json options into the subclass.
-
#json_create(hash) ⇒ Object
Create a new model object from the hash provided by parsing JSON.
-
#to_json(*a) ⇒ Object
Call the dataset
to_json
method.
Instance Attribute Details
#json_serializer_opts ⇒ Object (readonly)
The default opts to use when serializing model objects to JSON.
117 118 119 |
# File 'lib/sequel/plugins/json_serializer.rb', line 117 def json_serializer_opts @json_serializer_opts end |
Instance Method Details
#inherited(subclass) ⇒ Object
Copy the current model object’s default json options into the subclass.
150 151 152 153 154 155 |
# File 'lib/sequel/plugins/json_serializer.rb', line 150 def inherited(subclass) super opts = {} json_serializer_opts.each{|k, v| opts[k] = (v.is_a?(Array) || v.is_a?(Hash)) ? v.dup : v} subclass.instance_variable_set(:@json_serializer_opts, opts) end |
#json_create(hash) ⇒ Object
Create a new model object from the hash provided by parsing JSON. Handles column values (stored in values
), associations (stored in associations
), and other values (by calling a setter method). If an entry in the hash is not a column or an association, and no setter method exists, raises an Error.
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 |
# File 'lib/sequel/plugins/json_serializer.rb', line 124 def json_create(hash) obj = new cols = columns.map{|x| x.to_s} assocs = associations.map{|x| x.to_s} meths = obj.send(:setter_methods, nil, nil) hash.delete(JSON.create_id) hash.each do |k, v| if assocs.include?(k) obj.associations[k.to_sym] = v elsif meths.include?("#{k}=") obj.send("#{k}=", v) elsif cols.include?(k) obj.values[k.to_sym] = v else raise Error, "Entry in JSON hash not an association or column and no setter method exists: #{k}" end end obj end |
#to_json(*a) ⇒ Object
Call the dataset to_json
method.
145 146 147 |
# File 'lib/sequel/plugins/json_serializer.rb', line 145 def to_json(*a) dataset.to_json(*a) end |