Class: Serega::SeregaPresenter

Inherits:
SimpleDelegator
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/serega/presenter.rb

Overview

Wraps the serialized object, so computed attribute values can be defined as methods instead of :value callables.

SeregaPresenter inherits from SimpleDelegator:

  • All methods of the serialized object are available directly inside presenter methods.
  • Methods not defined on SeregaPresenter are resolved via method_missing on the first call and then defined as real delegators, so subsequent calls skip method_missing entirely.
  • The original object is accessible via getobj (standard SimpleDelegator API).
  • The serialization context is accessible via the private method ctx.

The presenter do ... end block is evaluated inside the serializer's own SeregaPresenter class, so multiple blocks accumulate.

Examples:

class UserSerializer < Serega
  attribute :name
  attribute :role

  presenter do
    def name
      [first_name, last_name].compact.join(' ') # first_name/last_name delegated to object
    end

    def role
      id == __ctx__[:current_user_id] ? :self : :other
    end
  end
end

Instance Method Summary collapse

Constructor Details

#initialize(object, ctx = nil) ⇒ SeregaPresenter

Returns a new instance of SeregaPresenter.

Parameters:

  • object (Object)

    Serialized object to wrap

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

    Serialization context



43
44
45
46
# File 'lib/serega/presenter.rb', line 43

def initialize(object, ctx = nil)
  super(object)
  @__ctx__ = ctx
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *_args, &_block) ⇒ Object (private)

Delegates all missing methods to serialized object.

Creates delegator method after first #method_missing hit to improve performance of following serializations.



58
59
60
61
62
# File 'lib/serega/presenter.rb', line 58

def method_missing(name, *_args, &_block) # rubocop:disable Style/MissingRespondToMissing -- base SimpleDelegator class has this method
  super.tap do
    self.class.def_delegator :__getobj__, name
  end
end