| 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 137
137: def from_json(json)
138: set(JSON.parse(json))
139: 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 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 160
160: def to_json(*a)
161: if opts = a.first.is_a?(Hash)
162: opts = model.json_serializer_opts.merge(a.first)
163: a = []
164: else
165: opts = model.json_serializer_opts
166: end
167: vals = values
168: cols = if only = opts[:only]
169: Array(only)
170: else
171: vals.keys - Array(opts[:except])
172: end
173: h = (JSON.create_id && !opts[:naked] && !opts[:root]) ? {JSON.create_id=>model.name} : {}
174: cols.each{|c| h[c.to_s] = vals[c]}
175: if inc = opts[:include]
176: if inc.is_a?(Hash)
177: inc.each do |k, v|
178: v = v.empty? ? [] : [v]
179: h[k.to_s] = case objs = send(k)
180: when Array
181: objs.map{|obj| Literal.new(obj.to_json(*v))}
182: else
183: Literal.new(objs.to_json(*v))
184: end
185: end
186: else
187: Array(inc).each{|c| h[c.to_s] = send(c)}
188: end
189: end
190: h = {model.send(:underscore, model.to_s) => h} if opts[:root]
191: h.to_json(*a)
192: end