Module: Pragma::Decorator::Type

Defined in:
lib/pragma/decorator/type.rb

Overview

Adds a type property containing the machine-readable type of the represented object.

This is useful for the client to understand what kind of resource it’s dealing with and trigger related logic.

Examples:

Including the resource’s type

class ArticleDecorator < Pragma::Decorator::Base
  include Pragma::Decorator::Type
end

# {
#   "type": "article"
# }
ArticleDecorator.new(article).to_hash

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



21
22
23
24
25
# File 'lib/pragma/decorator/type.rb', line 21

def included(klass)
  klass.class_eval do
    property :type, exec_context: :decorator, render_nil: false
  end
end

.overridesHash{String => String}

Returns the type overrides.

By default, Array and ActiveRecord::Relation are renamed to list.

Returns:

  • (Hash{String => String})

    a hash of class-override pairs



32
33
34
35
36
37
# File 'lib/pragma/decorator/type.rb', line 32

def overrides
  @overrides ||= {
    'Array' => 'list',
    'ActiveRecord::Relation' => 'list'
  }
end

Instance Method Details

#typeString

Returns the type to expose to API clients.

If an override is present for the decorated class, returns the override, otherwise returns the underscored class.

Returns:

  • (String)

    type to expose

See Also:



48
49
50
51
# File 'lib/pragma/decorator/type.rb', line 48

def type
  Pragma::Decorator::Type.overrides[decorated.class.name] ||
    underscore_klass(decorated.class.name)
end