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:



352
353
354
# File 'lib/serega.rb', line 352

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)

    Serializer modifiers and other instantiating 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



364
365
366
367
368
369
370
# File 'lib/serega.rb', line 364

def call(object, opts = nil)
  opts = opts ? opts.transform_keys!(&:to_sym) : {}
  self.class::CheckSerializeParams.new(opts).validate unless opts.empty?

  opts[:context] ||= {}
  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)



333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'lib/serega.rb', line 333

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

#preloadsHash

Returns merged preloads of all serialized attributes.

Returns:

  • (Hash)

    merged preloads of all serialized attributes



378
379
380
# File 'lib/serega.rb', line 378

def preloads
  @preloads ||= SeregaUtils::PreloadsConstructor.call(plan)
end

#to_h(object, opts = nil) ⇒ Object

See Also:



373
374
375
# File 'lib/serega.rb', line 373

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