Module: Serega::InstanceMethods

Included in:
Serega
Defined in:
lib/serega.rb

Overview

Core serializer instance methods

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#optsObject (readonly)

Returns the value of attribute opts.



190
191
192
# File 'lib/serega.rb', line 190

def opts
  @opts
end

Instance Method Details

#as_json(object, opts = FROZEN_EMPTY_HASH) ⇒ Hash

Serializes provided object as json (uses only JSON-compatible types) When you later serialize/deserialize it from JSON you should receive equal object

Parameters:

  • object (Object)

    Serialized object

Returns:

  • (Hash)

    Serialization result



243
244
245
246
# File 'lib/serega.rb', line 243

def as_json(object, opts = FROZEN_EMPTY_HASH)
  hash = to_h(object, opts)
  Utils::AsJSON.call(hash, to_json: self.class.config[:to_json])
end

#initialize(opts = FROZEN_EMPTY_HASH) ⇒ Object

Instantiates new Serega class

Parameters:

  • only (Array, Hash, String, Symbol)

    The only attributes to serialize

  • except (Array, Hash, String, Symbol)

    Attributes to hide

  • with (Array, Hash, String, Symbol)

    Attributes (usually hidden) to serialize additionally



199
200
201
202
203
# File 'lib/serega.rb', line 199

def initialize(opts = FROZEN_EMPTY_HASH)
  CheckAllowedKeys.call(opts, self.class.config[:initiate_keys])
  opts = prepare_modifiers(opts) if opts && (opts != FROZEN_EMPTY_HASH)
  @opts = opts
end

#to_h(object, opts = {}) ⇒ Hash

Serializes provided object to hash

Parameters:

  • object (Object)

    Serialized object

  • opts (Hash) (defaults to: {})

    Serialization options, like :context and :many

Returns:

  • (Hash)

    Serialization result



213
214
215
216
217
218
219
220
# File 'lib/serega.rb', line 213

def to_h(object, opts = {})
  CheckAllowedKeys.call(opts, self.class.config[:serialize_keys])
  CheckOptIsHash.call(opts, :context)
  CheckOptIsBool.call(opts, :many)
  opts[:context] ||= {}

  self.class::Convert.call(object, **opts, map: map)
end

#to_json(object, opts = FROZEN_EMPTY_HASH) ⇒ Hash

Serializes provided object to json

Parameters:

  • object (Object)

    Serialized object

Returns:

  • (Hash)

    Serialization result



229
230
231
232
# File 'lib/serega.rb', line 229

def to_json(object, opts = FROZEN_EMPTY_HASH)
  hash = to_h(object, opts)
  self.class.config[:to_json].call(hash)
end