Class: BetterService::Presenter

Inherits:
Object
  • Object
show all
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

  presenter_options do
    { current_user: user }
  end

  search_with do
    { items: Product.all.to_a }
  end
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, **options) ⇒ Presenter

Initialize presenter

Parameters:

  • object (Object)

    The object to present (e.g., ActiveRecord model)

  • options (Hash)

    Additional options (e.g., current_user, permissions)



51
52
53
54
# File 'lib/better_service/presenter.rb', line 51

def initialize(object, **options)
  @object = object
  @options = options
end

Instance Attribute Details

#objectObject (readonly)

Returns the value of attribute object.



45
46
47
# File 'lib/better_service/presenter.rb', line 45

def object
  @object
end

#optionsObject (readonly)

Returns the value of attribute options.



45
46
47
# File 'lib/better_service/presenter.rb', line 45

def options
  @options
end

Instance Method Details

#as_json(opts = {}) ⇒ Hash

Override in subclass to define JSON representation

Parameters:

  • opts (Hash) (defaults to: {})

    JSON serialization options

Returns:

  • (Hash)

    Hash representation of the object



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_hHash

Hash representation (alias for as_json)

Returns:

  • (Hash)

    Hash representation



80
81
82
# File 'lib/better_service/presenter.rb', line 80

def to_h
  as_json
end

#to_json(opts = {}) ⇒ String

JSON string representation

Parameters:

  • opts (Hash) (defaults to: {})

    JSON serialization options

Returns:

  • (String)

    JSON string



73
74
75
# File 'lib/better_service/presenter.rb', line 73

def to_json(opts = {})
  as_json(opts).to_json
end