module PresenterRails

Constants

VERSION

Public Class Methods

ivar_for(name) click to toggle source

Internal: Name of the instance variable used to memoize a presenter method.

# File lib/presenter_rails.rb, line 35
def self.ivar_for(name)
  "@_presenter_#{ name.to_s.gsub("?", "_query").gsub("!", "_bang") }"
end
method_name_for(name) click to toggle source

Internal: Name of the presenter method as defined in the controller.

# File lib/presenter_rails.rb, line 30
def self.method_name_for(name)
  "#{ name }_presenter"
end

Public Instance Methods

present(name, &block) click to toggle source

Public: Defines a method and makes it available to the view context under the specified name as a memoized variable.

name - The name of the method as called from the view context. block - Executed once if (and only if) the method is called.

Returns nothing.

# File lib/presenter_rails.rb, line 12
def present(name, &block)
  presenter_method = PresenterRails.method_name_for(name)
  ivar = PresenterRails.ivar_for(name)

  private define_method(presenter_method) {
    if instance_variable_defined?(ivar)
      instance_variable_get(ivar)
    else
      instance_variable_set(ivar, instance_exec(&block))
    end
  }

  helper Module.new {
    define_method(name) { controller.send(presenter_method) }
  }
end