Module | Sequel::Plugins::JsonSerializer::InstanceMethods |
In: |
lib/sequel/plugins/json_serializer.rb
|
Parse the provided JSON, which should return a hash, and call set with that hash.
# File lib/sequel/plugins/json_serializer.rb, line 142 142: def from_json(json, opts={}) 143: h = JSON.parse(json) 144: if fields = opts[:fields] 145: set_fields(h, fields, opts) 146: else 147: set(h) 148: end 149: end
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. |
# File lib/sequel/plugins/json_serializer.rb, line 170 170: def to_json(*a) 171: if opts = a.first.is_a?(Hash) 172: opts = model.json_serializer_opts.merge(a.first) 173: a = [] 174: else 175: opts = model.json_serializer_opts 176: end 177: vals = values 178: cols = if only = opts[:only] 179: Array(only) 180: else 181: vals.keys - Array(opts[:except]) 182: end 183: h = (JSON.create_id && !opts[:naked] && !opts[:root]) ? {JSON.create_id=>model.name} : {} 184: cols.each{|c| h[c.to_s] = send(c)} 185: if inc = opts[:include] 186: if inc.is_a?(Hash) 187: inc.each do |k, v| 188: v = v.empty? ? [] : [v] 189: h[k.to_s] = case objs = send(k) 190: when Array 191: objs.map{|obj| Literal.new(obj.to_json(*v))} 192: else 193: Literal.new(objs.to_json(*v)) 194: end 195: end 196: else 197: Array(inc).each{|c| h[c.to_s] = send(c)} 198: end 199: end 200: h = {model.send(:underscore, model.to_s) => h} if opts[:root] 201: h.to_json(*a) 202: end