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

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

Instance Method Summary collapse

Instance Method Details

#json_serializer_opts(opts = OPTS) ⇒ Object

Store default options used when calling to_json on this dataset. These options take precedence over the class level options, and can be overridden by passing options directly to to_json.



386
387
388
# File 'lib/sequel/plugins/json_serializer.rb', line 386

def json_serializer_opts(opts=OPTS)
  clone(:json_serializer_opts=>opts)
end

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

:instance_block

A block to pass to #to_json for each value in the dataset (or :array option).

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



406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# File 'lib/sequel/plugins/json_serializer.rb', line 406

def to_json(*a)
  opts = model.json_serializer_opts

  if ds_opts = @opts[:json_serializer_opts]
    opts = opts.merge(ds_opts)
  end

  if (arg = a.first).is_a?(Hash)
    opts = opts.merge(arg)
    a = []
  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 || @opts[:eager_graph] 
    array = if opts[:array]
      opts = opts.dup
      opts.delete(:array)
    else
      all
    end
    JsonSerializer.object_to_json_data(array, opts, &opts[:instance_block])
  else
    all
  end

  res = {collection_root => res} if collection_root
  res = yield res if defined?(yield)

  Sequel.object_to_json(res, *a)
end