Class: Toolx::Core::Presenter

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/toolx/core/presenter.rb

Constant Summary collapse

NoPresenterDetected =
Class.new(StandardError)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, **opts) ⇒ Presenter

Returns a new instance of Presenter.



4
5
6
7
# File 'lib/toolx/core/presenter.rb', line 4

def initialize(object, **opts)
  super(object)
  @__opts = opts || {}
end

Instance Attribute Details

#__optsObject (readonly)

Returns the value of attribute __opts.



9
10
11
# File 'lib/toolx/core/presenter.rb', line 9

def __opts
  @__opts
end

Class Method Details

.as_proc(*args, **kwargs, &block) ⇒ Object

Public: Returns a Proc that instantiates the presenter and optionally calls a method on it. Useful for transforming collections with presentation logic.

Example:

Model.all.map(&MyPresenter.as_proc(use: :to_json))


28
29
30
31
32
33
34
# File 'lib/toolx/core/presenter.rb', line 28

def self.as_proc(*args, **kwargs, &block)
  use = kwargs.delete(:use)
  ->(object) do
    presenter = present(object, *args, **kwargs, &block)
    use ? presenter.public_send(use) : presenter
  end
end

.auto_present(object) ⇒ Object



42
# File 'lib/toolx/core/presenter.rb', line 42

def self.auto_present(object) = detect(object).present(object)

.detect(object) ⇒ Object



36
37
38
39
40
# File 'lib/toolx/core/presenter.rb', line 36

def self.detect(object)
  object.class::Presenter
rescue NameError
  raise NoPresenterDetected, "No presenter detected for #{object.class.name}. Please define a Presenter constant in the class."
end

.present(*args, **kwargs, &block) ⇒ Object

Public: Constructs and returns a new presenter instance. Accepts flexible arguments to support subclasses with custom initializers.

Example:

MyPresenter.present(user, show_deleted: true)


17
# File 'lib/toolx/core/presenter.rb', line 17

def self.present(*args, **kwargs, &block) = new(*args, **kwargs, &block)

.to_procObject

Public: Returns a Proc that instantiates the presenter. Allows usage like: ‘Model.all.map(&MyPresenter)`



21
# File 'lib/toolx/core/presenter.rb', line 21

def self.to_proc = ->(object) { present(object) }

Instance Method Details

#original_objectObject



10
# File 'lib/toolx/core/presenter.rb', line 10

def original_object = __getobj__

#t(key, opts = {}) ⇒ Object



45
# File 'lib/toolx/core/presenter.rb', line 45

def t(key, opts = {}) = I18n.t([t_default_key, key].join('.'), **opts.merge(locale: __opts[:locale] || :pl))

#t!(key, opts = {}) ⇒ Object



44
# File 'lib/toolx/core/presenter.rb', line 44

def t!(key, opts = {}) = I18n.t!([t_default_key, key].join('.'), **opts.merge(locale: __opts[:locale] || :pl))

#t_default_keyObject



47
48
49
# File 'lib/toolx/core/presenter.rb', line 47

def t_default_key
  @t_default_key ||= self.class.name.sub(/Presenter$/, '').split('::').compact.join('.').underscore
end