module Sequel::Plugins::JsonSerializer::DatasetMethods

  1. lib/sequel/plugins/json_serializer.rb

Methods

Public Instance

  1. json_serializer_opts
  2. to_json

Public Instance methods

json_serializer_opts(opts=OPTS)

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.

[show source]
    # File lib/sequel/plugins/json_serializer.rb
382 def json_serializer_opts(opts=OPTS)
383   clone(:json_serializer_opts=>opts)
384 end
to_json(*a)

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.

[show source]
    # File lib/sequel/plugins/json_serializer.rb
402 def to_json(*a)
403   opts = model.json_serializer_opts
404 
405   if ds_opts = @opts[:json_serializer_opts]
406     opts = opts.merge(ds_opts)
407   end
408 
409   if (arg = a.first).is_a?(Hash)
410     opts = opts.merge(arg)
411     a = []
412   end
413 
414   case collection_root = opts[:root]
415   when nil, false, :instance
416     collection_root = false
417   else
418     opts = opts.dup
419     unless collection_root == :both
420       opts.delete(:root)
421     end
422     unless collection_root.is_a?(String)
423       collection_root = model.send(:pluralize, model.send(:underscore, model.send(:demodulize, model.to_s)))
424     end
425   end
426 
427   res = if row_proc || @opts[:eager_graph] 
428     array = if opts[:array]
429       opts = opts.dup
430       opts.delete(:array)
431     else
432       all
433     end
434     JsonSerializer.object_to_json_data(array, opts, &opts[:instance_block])
435   else
436     all
437   end
438 
439   res = {collection_root => res} if collection_root
440   res = yield res if defined?(yield)
441 
442   Sequel.object_to_json(res, *a)
443 end