Module: Serega::InstanceMethods

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

Overview

Serializers instance methods

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#planSerega::SeregaPlan (readonly)

Plan for serialization. This plan can be traversed to find serialized attributes and nested attributes.

Returns:



413
414
415
# File 'lib/serega.rb', line 413

def plan
  @plan
end

Instance Method Details

#call(object, opts = nil) ⇒ Hash

Serializes provided object to Hash

Parameters:

  • object (Object)

    Serialized object

  • opts (Hash, nil) (defaults to: nil)

    Serializing options

Options Hash (opts):

  • :context (Hash)

    Serialization context

  • :many (Boolean)

    Set true if provided multiple objects (Default object.is_a?(Enumerable))

Returns:

  • (Hash)

    Serialization result



425
426
427
428
# File 'lib/serega.rb', line 425

def call(object, opts = nil)
  opts = prepare_initial_serialization_opts(object, opts)
  serialize(object, opts)
end

#initialize(opts = nil) ⇒ Object

Instantiates new Serega class

Parameters:

  • opts (Hash, nil) (defaults to: nil)

    Serializer modifiers and other instantiating options

Options Hash (opts):

  • :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

  • :validate (Boolean)

    Validates provided modifiers (Default is true)



394
395
396
397
398
399
400
401
402
403
404
405
406
# File 'lib/serega.rb', line 394

def initialize(opts = nil)
  @opts =
    if opts.nil? || opts.empty?
      FROZEN_EMPTY_HASH
    else
      opts.transform_keys!(&:to_sym)
      parse_modifiers(opts)
    end

  self.class::CheckInitiateParams.new(@opts).validate if opts&.fetch(:check_initiate_params) { config.check_initiate_params }

  @plan = self.class::SeregaPlan.call(@opts)
end

#to_data(object, opts = nil) ⇒ Data

Serializes provided object to Data objects Patched in:

  • plugin :root (adds a data-object for a root level keys)

Parameters:

  • object (Object)

    Serialized object

  • opts (Hash, nil) (defaults to: nil)

    Serializing options

Options Hash (opts):

  • :context (Hash)

    Serialization context

  • :many (Boolean)

    Set true if provided multiple objects (Default object.is_a?(Enumerable))

Returns:

  • (Data)

    Serialization result



447
448
449
450
451
# File 'lib/serega.rb', line 447

def to_data(object, opts = nil)
  opts = prepare_initial_serialization_opts(object, opts)
  serialized_data = serialize(object, opts)
  self.class::SeregaDataBuilder.call(self, serialized_data)
end

#to_h(object, opts = nil) ⇒ Object

See Also:



431
432
433
# File 'lib/serega.rb', line 431

def to_h(object, opts = nil)
  call(object, opts)
end