Module: Sequel::Plugins::JsonSerializer::InstanceMethods

Defined in:
lib/sequel/plugins/json_serializer.rb

Instance Method Summary collapse

Instance Method Details

#from_json(json, opts = {}) ⇒ Object

Parse the provided JSON, which should return a hash, and process the hash with from_json_node.



197
198
199
200
201
202
# File 'lib/sequel/plugins/json_serializer.rb', line 197

def from_json(json, opts={})
  if opts[:all_associations] || opts[:all_columns]
    Sequel::Deprecation.deprecate("The from_json :all_associations and :all_columns", 'You need to explicitly specify the associations and columns via the :associations and :fields options')
  end
  from_json_node(Sequel.parse_json(json), opts)
end

#from_json_node(hash, opts = {}) ⇒ Object

Using the provided hash, update the instance with data contained in the hash. By default, just calls set with the hash values.

Options:

:all_associations

Indicates that all associations supported by the model should be tried. This option also cascades to associations if used. It is better to use the :associations option instead of this option. This option only exists for backwards compatibility.

:all_columns

Overrides the setting logic allowing all setter methods be used, even if access to the setter method is restricted. This option cascades to associations if used, and can be reset in those associations using the :all_columns=>false or :fields options. This option is considered a security risk, and only exists for backwards compatibility. It is better to use the :fields option appropriately instead of this option, or no option at all.

:associations

Indicates that the associations cache should be updated by creating a new associated object using data from the hash. Should be a Symbol for a single association, an array of symbols for multiple associations, or a hash with symbol keys and dependent association option hash values.

:fields

Changes the behavior to call set_fields using the provided fields, instead of calling set.



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/sequel/plugins/json_serializer.rb', line 223

def from_json_node(hash, opts={})
  unless hash.is_a?(Hash)
    raise Error, "parsed json doesn't return a hash"
  end
  if hash.has_key?(JSON.create_id)
    Sequel::Deprecation.deprecate('Attempting to use Model#from_json with a hash value that includes JSON.create_id is deprecated.  Starting in Sequel 4.0, the create_id will not be removed automatically.')
    hash.delete(JSON.create_id)
  end

  unless assocs = opts[:associations]
    if opts[:all_associations]
      assocs = {}
      model.associations.each{|v| assocs[v] = {:all_associations=>true}}
    end
  end

  if assocs
    assocs = case assocs
    when Symbol
      {assocs=>{}}
    when Array
      assocs_tmp = {}
      assocs.each{|v| assocs_tmp[v] = {}}
      assocs_tmp
    when Hash
      assocs
    else
      raise Error, ":associations should be Symbol, Array, or Hash if present"
    end

    if opts[:all_columns]
      assocs.each_value do |assoc_opts|
        assoc_opts[:all_columns] = true unless assoc_opts.has_key?(:fields) || assoc_opts.has_key?(:all_columns)
      end
    end

    assocs.each do |assoc, assoc_opts|
      if assoc_values = hash.delete(assoc.to_s)
        unless r = model.association_reflection(assoc)
          raise Error, "Association #{assoc} is not defined for #{model}"
        end

        associations[assoc] = if r.returns_array?
          raise Error, "Attempt to populate array association with a non-array" unless assoc_values.is_a?(Array)
          assoc_values.map{|v| v.is_a?(r.associated_class) ? v : r.associated_class.new.from_json_node(v, assoc_opts)}
        else
          raise Error, "Attempt to populate non-array association with an array" if assoc_values.is_a?(Array)
          assoc_values.is_a?(r.associated_class) ? assoc_values : r.associated_class.new.from_json_node(assoc_values, assoc_opts)
        end
      end
    end
  end

  if fields = opts[:fields]
    set_fields(hash, fields, opts)
  elsif opts[:all_columns]
    meths = methods.collect{|x| x.to_s}.grep(Model::SETTER_METHOD_REGEXP) - Model::RESTRICTED_SETTER_METHODS
    hash.each do |k, v|
      if meths.include?(setter_meth = "#{k}=")
        send(setter_meth, v)
      else
        raise Error, "Entry in JSON does not have a matching setter method: #{k}"
      end
    end
  else
    set(hash)
  end

  self
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.

: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.



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/sequel/plugins/json_serializer.rb', line 310

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 = {}
  if  JSON.create_id && !opts[:naked] && !opts[:root]
    Sequel::Deprecation.deprecate('The :naked and :root options have not been used, so adding JSON.create_id to the to_json output.  This is deprecated, starting in Sequel 4, the JSON.create_id will never be added.')
    h[JSON.create_id] = model.name
  end

  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(Sequel.object_to_json(obj, *v))}
        else
          Literal.new(Sequel.object_to_json(objs, *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]
  Sequel.object_to_json(h, *a)
end