Module: Sequel::Plugins::JsonSerializer::InstanceMethods
- Defined in:
- lib/sequel/plugins/json_serializer.rb
Instance Method Summary collapse
-
#from_json(json) ⇒ Object
Parse the provided JSON, which should return a hash, and call
set
with that hash. -
#to_json(*a) ⇒ Object
Return a string in JSON format.
Instance Method Details
#from_json(json) ⇒ Object
Parse the provided JSON, which should return a hash, and call set
with that hash.
137 138 139 |
# File 'lib/sequel/plugins/json_serializer.rb', line 137 def from_json(json) set(JSON.parse(json)) end |
#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.
- :naked
-
Not to add the JSON.create_id 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.
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 |
# File 'lib/sequel/plugins/json_serializer.rb', line 160 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 |