module Sequel::Plugins::JsonSerializer::DatasetMethods
Public Instance Methods
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.
# File lib/sequel/plugins/json_serializer.rb 375 def json_serializer_opts(opts=OPTS) 376 clone(:json_serializer_opts=>opts) 377 end
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.
# File lib/sequel/plugins/json_serializer.rb 395 def to_json(*a) 396 opts = model.json_serializer_opts 397 398 if ds_opts = @opts[:json_serializer_opts] 399 opts = opts.merge(ds_opts) 400 end 401 402 if (arg = a.first).is_a?(Hash) 403 opts = opts.merge(arg) 404 a = [] 405 end 406 407 case collection_root = opts[:root] 408 when nil, false, :instance 409 collection_root = false 410 else 411 opts = opts.dup 412 unless collection_root == :both 413 opts.delete(:root) 414 end 415 unless collection_root.is_a?(String) 416 collection_root = model.send(:pluralize, model.send(:underscore, model.send(:demodulize, model.to_s))) 417 end 418 end 419 420 res = if row_proc || @opts[:eager_graph] 421 array = if opts[:array] 422 opts = opts.dup 423 opts.delete(:array) 424 else 425 all 426 end 427 array.map{|obj| Literal.new(Sequel.object_to_json(obj, opts, &opts[:instance_block]))} 428 else 429 all 430 end 431 432 res = {collection_root => res} if collection_root 433 res = yield res if block_given? 434 435 Sequel.object_to_json(res, *a) 436 end