Class: Hc::Presenter::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/hc/presenter/base.rb

Overview

Creates a platform for other presenters to serialize objects into hashes

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object:, controller_context: nil, options: {}) ⇒ Base

Initialization of required and optional instance variables



11
12
13
14
15
# File 'lib/hc/presenter/base.rb', line 11

def initialize(object:, controller_context: nil, options: {})
  @object = object
  @options = options.try(:to_h).to_h.symbolize_keys
  @controller_context = controller_context
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args, &block) ⇒ Object (private)

This method passes off missing methods to the controller context, thus allowing us access to that controller’s methods in the presenters. This should be used with care, and should only really be used for authorization control and permissions-based conditional content.



47
48
49
50
# File 'lib/hc/presenter/base.rb', line 47

def method_missing(*args, &block)
  return nil unless @controller_context
  @controller_context.send(*args, &block)
end

Class Method Details

.presents(name) ⇒ Object

Abstraction method for nicer top-level access to object context with a friendly name, plus allow access to any options that were passed in.



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/hc/presenter/base.rb', line 20

def self.presents(name)
  define_method(name) do
    @object
  end
  define_method(:options) do
    @options
  end
  define_method(:controller_context) do
    @controller_context
  end
end

Instance Method Details

#present(object, klass: nil, options: nil, method: nil) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/hc/presenter/base.rb', line 32

def present(object, klass: nil, options: nil, method: nil)
  if @controller_context
    @controller_context.present(object, klass: klass, options: options || @options, method: method)
  else
    Hc::Presenter.present(object, klass: klass, method: method, options: options)
  end
end