Method: Sequel::Plugins::JsonSerializer::InstanceMethods#to_json

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

#to_json(*a) ⇒ Object

Return a string in JSON format. Accepts the following options:

:except

Symbol or Array of Symbols of columns not to include in the JSON output.

:include

Symbol, Array of Symbols, or a Hash with Symbol keys and Hash values specifying associations or other non-column attributes to include in the JSON output. Using a nested hash, you can pass options to associations to affect the JSON used for associated objects.

:only

Symbol or Array of Symbols of columns to only include in the JSON output, ignoring all other columns.

:root

Qualify the JSON with the name of the object. If a string is given, use the string as the key, otherwise use an underscored version of the model’s name.



310
311
312
313
314
315
316
317
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
357
358
359
360
361
362
363
364
# File 'lib/sequel/plugins/json_serializer.rb', line 310

def to_json(*a)
  opts = model.json_serializer_opts
  opts = opts.merge(@json_serializer_opts) if @json_serializer_opts
  if (arg_opts = a.first).is_a?(Hash)
    opts = opts.merge(arg_opts)
    a = []
  end

  vals = values
  cols = if only = opts[:only]
    Array(only)
  else
    vals.keys - Array(opts[:except])
  end

  h = {}

  cols.each{|c| h[c.to_s] = get_column_value(c)}
  if inc = opts[:include]
    if inc.is_a?(Hash)
      inc.each do |k, v|
        if k.is_a?(Sequel::SQL::AliasedExpression)
          key_name = k.alias.to_s
          k = k.expression
        else
          key_name = k.to_s
        end

        v = v.empty? ? [] : [v]
        h[key_name] = JsonSerializer.object_to_json_data(public_send(k), *v)
      end
    else
      Array(inc).each do |c|
        if c.is_a?(Sequel::SQL::AliasedExpression)
          key_name = c.alias.to_s
          c = c.expression
        else
          key_name = c.to_s
        end

        h[key_name] = JsonSerializer.object_to_json_data(public_send(c))
      end
    end
  end

  if root = opts[:root]
    unless root.is_a?(String)
      root = model.send(:underscore, model.send(:demodulize, model.to_s))
    end
    h = {root => h}
  end

  h = yield h if defined?(yield)
  Sequel.object_to_json(h, *a)
end