Module: Serega::SeregaPlugins::Presenter

Defined in:
lib/serega/plugins/presenter/presenter.rb

Overview

Plugin :presenter — moves computed attribute logic into a dedicated Presenter class.

Presenter inherits from SimpleDelegator:

  • All methods of the serialized object are available directly inside presenter methods.
  • Methods not defined on Presenter 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 Presenter class, so multiple blocks accumulate.

Examples:

class UserSerializer < Serega
  plugin :presenter

  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

Defined Under Namespace

Modules: ClassMethods, SeregaObjectSerializerInstanceMethods Classes: Presenter

Class Method Summary collapse

Class Method Details

.after_load_plugin(serializer_class, **_opts) ⇒ void

This method returns an undefined value.

Runs callbacks after plugin was attached

Parameters:

  • serializer_class (Class<Serega>)

    Current serializer class

  • _opts (Hash)

    Plugin options



69
70
71
72
73
74
75
76
77
78
# File 'lib/serega/plugins/presenter/presenter.rb', line 69

def self.after_load_plugin(serializer_class, **_opts)
  presenter_class = Class.new(Presenter)
  presenter_class.serializer_class = serializer_class
  serializer_class.const_set(:Presenter, presenter_class)

  # The presenter's unwrap method returns the serialized object itself,
  # not an association — it must never be auto-preloaded.
  config = serializer_class.config
  config.auto_preload_excluded_methods = config.auto_preload_excluded_methods | [:__getobj__]
end

.load_plugin(serializer_class, **_opts) ⇒ void

This method returns an undefined value.

Applies plugin code to specific serializer

Parameters:

  • serializer_class (Class<Serega>)

    Current serializer class

  • _opts (Hash)

    Plugin options



55
56
57
58
# File 'lib/serega/plugins/presenter/presenter.rb', line 55

def self.load_plugin(serializer_class, **_opts)
  serializer_class.extend(ClassMethods)
  serializer_class::SeregaObjectSerializer.include(SeregaObjectSerializerInstanceMethods)
end

.plugin_nameSymbol

Returns Plugin name.

Returns:

  • (Symbol)

    Plugin name



42
43
44
# File 'lib/serega/plugins/presenter/presenter.rb', line 42

def self.plugin_name
  :presenter
end