Class: AsJsonPresentable::Presenter

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

Overview

Base JSON presenter class

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(resource) ⇒ Presenter

Returns a new instance of Presenter.



6
7
8
# File 'lib/as_json_presentable/presenter.rb', line 6

def initialize(resource)
  @resource = resource
end

Instance Attribute Details

#resourceObject (readonly)

Returns the value of attribute resource.



4
5
6
# File 'lib/as_json_presentable/presenter.rb', line 4

def resource
  @resource
end

Instance Method Details

#as_json(options = nil) ⇒ Object

Looks for the option ‘:presenter_action`. If it exists, looks for a method called `#as_<presenter_action>_json` and delegates to that method. If `:presenter_action` isn’t in the options, or it references a method that the presenter doesn’t respond to, falls back to the resource’s ‘#as_json` implementation.

e.g.

‘presenter.as_json(presenter_action: :index)`

will delegate to

‘presenter.as_index_json`



24
25
26
27
28
29
30
31
32
# File 'lib/as_json_presentable/presenter.rb', line 24

def as_json(options=nil)
  presenter_action = (options || {}).delete(:presenter_action)

  if has_presenter_method?(presenter_action)
    send(presenter_method(presenter_action), options)
  else
    resource.as_json(options)
  end
end