Module: Sequel::Plugins::JsonSerializer::DatasetMethods

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

Instance Method Summary collapse

Instance Method Details

#to_json(*a) ⇒ Object

Return a JSON string representing an array of all objects in this dataset. Takes the same options as the instance method, and passes them to every instance. Additionally, respects the following options:

:array

An array of instances. If this is not provided, calls #all on the receiver to get the array.

:root

If set to :collection, wraps the collection in a root object using the pluralized, underscored model name as the key. If set to :instance, only wraps the instances in a root object. If set to :both, wraps both the collection and instances in a root object. If set to a string, wraps the collection in a root object using the string as the key.



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
349
350
351
352
353
354
355
356
# File 'lib/sequel/plugins/json_serializer.rb', line 318

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

  case collection_root = opts[:root]
  when nil, false, :instance
    collection_root = false
  else
    opts = opts.dup
    unless collection_root == :both
      opts.delete(:root)
    end
    unless collection_root.is_a?(String)
      collection_root = model.send(:pluralize, model.send(:underscore, model.send(:demodulize, model.to_s)))
    end
  end

  res = if row_proc 
    array = if opts[:array]
      opts = opts.dup
      opts.delete(:array)
    else
      all
    end
    array.map{|obj| Literal.new(Sequel.object_to_json(obj, opts))}
   else
    all
  end

  if collection_root
    Sequel.object_to_json({collection_root => res}, *a)
  else
    Sequel.object_to_json(res, *a)
  end
end