Class: Bourgeois::Presenter

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, view = nil) ⇒ Presenter

Returns a new instance of Presenter.



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

def initialize(object, view = nil)
  @view = view
  super(@object = object)
end

Instance Attribute Details

#objectObject (readonly)

Return the original delegated object



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

def object
  @object
end

Class Method Details

.helper(name, opts = {}) ⇒ Object

Declare a new block helper method

Examples:

class UserPresenter < Bourgeois::Presenter
  helper :with_profile, if: -> { profile.present? }
end

presenter = UserPresenter.new(User.new(profile: 'Foo'))
presenter.with_profile do
  puts 'User has a profile:'
  puts presenter.profile
end


44
45
46
47
48
# File 'lib/bourgeois/presenter.rb', line 44

def self.helper(name, opts = {})
  define_method(name) do |&block|
    execute_helper(block, opts)
  end
end

.human_attribute_name(*args) ⇒ Object

ActionView::Helpers::FormBuilder needs this too



28
29
30
# File 'lib/bourgeois/presenter.rb', line 28

def self.human_attribute_name(*args)
  klass.human_attribute_name(*args)
end

.model_nameObject

ActionView::Helpers::FormBuilder needs this



23
24
25
# File 'lib/bourgeois/presenter.rb', line 23

def self.model_name
  klass.model_name
end

.present(object, klass = nil, view = nil) {|presenter| ... } ⇒ Object

Wrap a resource or a collection into its related presenter

Examples:

present User.new(name: 'Remi') do |user|
  puts user.inspect # => #<UserPresenter object=#<User name="Remi>>
  puts user.name # => Remi
end

Yields:

  • (presenter)


57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/bourgeois/presenter.rb', line 57

def self.present(object, klass = nil, view = nil, &blk)
  return if object.nil?
  return object.map { |o| present(o, klass, view, &blk) } if object.respond_to?(:to_a) && !object.is_a?(Struct)

  if object.is_a?(Bourgeois::Presenter)
    presenter = object
  else
    klass ||= presenter_class(object)
  end

  presenter ||= klass.new(object, view)
  yield presenter if block_given?

  presenter
end

Instance Method Details

#inspectObject

Return a String representation of the presenter + the original object



12
13
14
# File 'lib/bourgeois/presenter.rb', line 12

def inspect
  "#<#{self.class} object=#{@object.inspect}>"
end

#kind_of?(mod) ⇒ Boolean

We need to explicitely define this method because it’s not catched by the delegator

Returns:

  • (Boolean)


18
19
20
# File 'lib/bourgeois/presenter.rb', line 18

def kind_of?(mod)
  @object.kind_of?(mod)
end