module Sequel::Plugins::JsonSerializer::InstanceMethods

Public Instance Methods

from_json(json, opts={}) click to toggle source

Parse the provided JSON, which should return a hash, and call set with that hash.

# File lib/sequel/plugins/json_serializer.rb, line 161
def from_json(json, opts={})
  h = JSON.parse(json)
  if fields = opts[:fields]
    set_fields(h, fields, opts)
  else
    set(h)
  end
end
to_json(*a) click to toggle source

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.

:naked

Not to add the JSON.create_id (json_class) key to the JSON output hash, so when the JSON is parsed, it will yield a hash instead of a model object.

: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. Implies :naked since the object name is explicit.

# File lib/sequel/plugins/json_serializer.rb, line 189
def to_json(*a)
  if opts = a.first.is_a?(Hash)
    opts = model.json_serializer_opts.merge(a.first)
    a = []
  else
    opts = model.json_serializer_opts
  end
  vals = values
  cols = if only = opts[:only]
    Array(only)
  else
    vals.keys - Array(opts[:except])
  end
  h = (JSON.create_id && !opts[:naked] && !opts[:root]) ? {JSON.create_id=>model.name} : {}
  cols.each{|c| h[c.to_s] = send(c)}
  if inc = opts[:include]
    if inc.is_a?(Hash)
      inc.each do |k, v|
        v = v.empty? ? [] : [v]
        h[k.to_s] = case objs = send(k)
        when Array
          objs.map{|obj| Literal.new(obj.to_json(*v))}
        else
          Literal.new(objs.to_json(*v))
        end
      end
    else
      Array(inc).each{|c| h[c.to_s] = send(c)}
    end
  end
  h = {model.send(:underscore, model.to_s) => h} if opts[:root]
  h.to_json(*a)
end