Module: Sequel::Plugins::JsonSerializer::ClassMethods

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#json_serializer_optsObject (readonly)

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



93
94
95
# File 'lib/sequel/plugins/json_serializer.rb', line 93

def json_serializer_opts
  @json_serializer_opts
end

Instance Method Details

#inherited(subclass) ⇒ Object

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



126
127
128
129
130
131
# File 'lib/sequel/plugins/json_serializer.rb', line 126

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) ⇒ Object

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.



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/sequel/plugins/json_serializer.rb', line 100

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) ⇒ Object

Call the dataset to_json method.



121
122
123
# File 'lib/sequel/plugins/json_serializer.rb', line 121

def to_json(*a)
  dataset.to_json(*a)
end