module Sequel::Plugins::JsonSerializer::ClassMethods

Attributes

json_serializer_opts[R]

The default opts to use when serializing model objects to JSON.

Public Instance Methods

inherited(subclass) click to toggle source

Copy the current model object's default json options into the subclass.

# File lib/sequel/plugins/json_serializer.rb, line 131
def inherited(subclass)
  super
  opts = {}
  json_serializer_opts.each{|k, v| opts[k] = (v.is_a?(Array) || v.is_a?(Hash)) ? v.dup : v}
  subclass.instance_variable_set(:@json_serializer_opts, opts)
end
json_create(hash) click to toggle source

Create a new model object from the hash provided by parsing JSON. Handles column values (stored in values), associations (stored in associations), and other values (by calling a setter method). If an entry in the hash is not a column or an association, and no setter method exists, raises an Error.

# File lib/sequel/plugins/json_serializer.rb, line 105
def json_create(hash)
  obj = new
  cols = columns.map{|x| x.to_s}
  assocs = associations.map{|x| x.to_s}
  meths = obj.send(:setter_methods, nil, nil)
  hash.delete(JSON.create_id)
  hash.each do |k, v|
    if assocs.include?(k)
      obj.associations[k.to_sym] = v
    elsif meths.include?("#{k}=")
      obj.send("#{k}=", v)
    elsif cols.include?(k)
      obj.values[k.to_sym] = v
    else
      raise Error, "Entry in JSON hash not an association or column and no setter method exists: #{k}"
    end
  end
  obj
end
to_json(*a) click to toggle source

Call the dataset to_json method.

# File lib/sequel/plugins/json_serializer.rb, line 126
def to_json(*a)
  dataset.to_json(*a)
end