Sha256: 67fd00438208bf4281508c093b9d743011d6a29a3aa82f75120d165fb47caa74

Contents?: true

Size: 1.82 KB

Versions: 3

Compression:

Stored size: 1.82 KB

Contents

module Bourgeois
  class Presenter < ::SimpleDelegator
    def initialize(object, view = nil)
      @view = view
      super(@object = object)
    end

    # Return a String representation of the presenter + the original object
    def inspect
      "#<#{self.class} object=#{@object.inspect}>"
    end

    # We need to explicitely define this method because it's not
    # catched by the delegator
    def kind_of?(mod)
      @object.kind_of?(mod)
    end

    # ActionView::Helpers::FormBuilder needs this
    def self.model_name
      klass.model_name
    end

    # ActionView::Helpers::FormBuilder needs this too
    def self.human_attribute_name(*args)
      klass.human_attribute_name(*args)
    end

    # Declare a new block helper method
    #
    # @example
    #   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
    def self.helper(name, opts = {})
      define_method(name) do |&block|
        execute = true

        if opts[:if]
          execute = execute && self.instance_exec(&opts[:if])
        end

        if opts[:unless]
          execute = execute && !self.instance_exec(&opts[:unless])
        end

        block.call if execute
      end
    end

  private

    # Return the view from where the presenter was created
    def view
      @view
    end

    # Return the original delegated object
    def object
      @object
    end

    # Return the original object class based on the presenter class name
    # We would be able to use `@object.class` but we need this in class methods
    def self.klass
      @klass ||= self.name.split(/Presenter$/).first.constantize
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
bourgeois-1.0 lib/bourgeois/presenter.rb
bourgeois-0.1.5 lib/bourgeois/presenter.rb
bourgeois-0.1.3 lib/bourgeois/presenter.rb