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
386 def json_serializer_opts(opts=OPTS)
387   clone(:json_serializer_opts=>opts)
388 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
406 def to_json(*a)
407   opts = model.json_serializer_opts
408 
409   if ds_opts = @opts[:json_serializer_opts]
410     opts = opts.merge(ds_opts)
411   end
412 
413   if (arg = a.first).is_a?(Hash)
414     opts = opts.merge(arg)
415     a = []
416   end
417 
418   case collection_root = opts[:root]
419   when nil, false, :instance
420     collection_root = false
421   else
422     opts = opts.dup
423     unless collection_root == :both
424       opts.delete(:root)
425     end
426     unless collection_root.is_a?(String)
427       collection_root = model.send(:pluralize, model.send(:underscore, model.send(:demodulize, model.to_s)))
428     end
429   end
430 
431   res = if row_proc || @opts[:eager_graph] 
432     array = if opts[:array]
433       opts = opts.dup
434       opts.delete(:array)
435     else
436       all
437     end
438     JsonSerializer.object_to_json_data(array, opts, &opts[:instance_block])
439   else
440     all
441   end
442 
443   res = {collection_root => res} if collection_root
444   res = yield res if defined?(yield)
445 
446   Sequel.object_to_json(res, *a)
447 end