Module: Sequel::Plugins::JsonSerializer::InstanceMethods
- Defined in:
- lib/sequel/plugins/json_serializer.rb
Instance Method Summary collapse
-
#from_json(json, opts = {}) ⇒ Object
Parse the provided JSON, which should return a hash, and call
set
with that hash. -
#to_json(*a) ⇒ Object
Return a string in JSON format.
Instance Method Details
#from_json(json, opts = {}) ⇒ Object
Parse the provided JSON, which should return a hash, and call set
with that hash.
161 162 163 164 165 166 167 168 |
# File 'lib/sequel/plugins/json_serializer.rb', line 161 def from_json(json, opts={}) h = JSON.parse(json) if fields = opts[:fields] set_fields(h, fields, opts) else set(h) end end |
#to_json(*a) ⇒ Object
Return a string in JSON format. Accepts the following options:
- :except
-
Symbol or Array of Symbols of columns not to include in the JSON output.
- :include
-
Symbol, Array of Symbols, or a Hash with Symbol keys and Hash values specifying associations or other non-column attributes to include in the JSON output. Using a nested hash, you can pass options to associations to affect the JSON used for associated objects.
- :naked
-
Not to add the JSON.create_id (json_class) key to the JSON output hash, so when the JSON is parsed, it will yield a hash instead of a model object.
- :only
-
Symbol or Array of Symbols of columns to only include in the JSON output, ignoring all other columns.
- :root
-
Qualify the JSON with the name of the object. Implies :naked since the object name is explicit.
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 |
# File 'lib/sequel/plugins/json_serializer.rb', line 189 def to_json(*a) if opts = a.first.is_a?(Hash) opts = model.json_serializer_opts.merge(a.first) a = [] else opts = model.json_serializer_opts end vals = values cols = if only = opts[:only] Array(only) else vals.keys - Array(opts[:except]) end h = (JSON.create_id && !opts[:naked] && !opts[:root]) ? {JSON.create_id=>model.name} : {} cols.each{|c| h[c.to_s] = send(c)} if inc = opts[:include] if inc.is_a?(Hash) inc.each do |k, v| v = v.empty? ? [] : [v] h[k.to_s] = case objs = send(k) when Array objs.map{|obj| Literal.new(obj.to_json(*v))} else Literal.new(objs.to_json(*v)) end end else Array(inc).each{|c| h[c.to_s] = send(c)} end end h = {model.send(:underscore, model.to_s) => h} if opts[:root] h.to_json(*a) end |