Class: BetterService::Presenter
- Inherits:
-
Object
- Object
- BetterService::Presenter
- Defined in:
- lib/better_service/presenter.rb
Overview
Presenter - Base class for presenting service data
Presenters transform raw model data into view-friendly formats. They are typically used with the Presentable concern’s presenter DSL.
Example:
class ProductPresenter < BetterService::Presenter
def as_json(opts = {})
{
id: object.id,
name: object.name,
price_formatted: "$#{object.price}",
available: object.stock > 0,
# Conditional fields based on current user
**(admin_fields if current_user&.admin?)
}
end
private
def admin_fields
{
cost: object.cost,
margin: object.price - object.cost
}
end
end
Usage with services:
class Products::IndexService < IndexService
presenter ProductPresenter
do
{ current_user: user }
end
search_with do
{ items: Product.all.to_a }
end
end
Instance Attribute Summary collapse
-
#object ⇒ Object
readonly
Returns the value of attribute object.
-
#options ⇒ Object
readonly
Returns the value of attribute options.
Instance Method Summary collapse
-
#as_json(opts = {}) ⇒ Hash
Override in subclass to define JSON representation.
-
#initialize(object, **options) ⇒ Presenter
constructor
Initialize presenter.
-
#to_h ⇒ Hash
Hash representation (alias for as_json).
-
#to_json(opts = {}) ⇒ String
JSON string representation.
Constructor Details
#initialize(object, **options) ⇒ Presenter
Initialize presenter
51 52 53 54 |
# File 'lib/better_service/presenter.rb', line 51 def initialize(object, **) @object = object = end |
Instance Attribute Details
#object ⇒ Object (readonly)
Returns the value of attribute object.
45 46 47 |
# File 'lib/better_service/presenter.rb', line 45 def object @object end |
#options ⇒ Object (readonly)
Returns the value of attribute options.
45 46 47 |
# File 'lib/better_service/presenter.rb', line 45 def end |
Instance Method Details
#as_json(opts = {}) ⇒ Hash
Override in subclass to define JSON representation
60 61 62 63 64 65 66 67 |
# File 'lib/better_service/presenter.rb', line 60 def as_json(opts = {}) # Default implementation delegates to object if object.respond_to?(:as_json) object.as_json(opts) else { data: object } end end |
#to_h ⇒ Hash
Hash representation (alias for as_json)
80 81 82 |
# File 'lib/better_service/presenter.rb', line 80 def to_h as_json end |
#to_json(opts = {}) ⇒ String
JSON string representation
73 74 75 |
# File 'lib/better_service/presenter.rb', line 73 def to_json(opts = {}) as_json(opts).to_json end |