Sha256: 74ccc80f3d9c04260b8595d8f6cbf9868454b7b84a1eb02190cf55472b13a442

Contents?: true

Size: 1.49 KB

Versions: 20

Compression:

Stored size: 1.49 KB

Contents

module Kadmin
  # Base presenter class
  class Presenter < SimpleDelegator
    # @param [Object] object the object to present
    # @param [ActiveView::Base] view the view to present in; can be provided later on
    def initialize(object, view: nil)
      super(object)
      @view = view
    end

    # Renders the wrapped object into the given view
    # @param [ActiveView::Base] view optionally render in a different view
    # @param [Hash] options additional options passed to the render method
    # @param [Proc] block optional block to render additional stuff within the template
    # @return [Object] rendered representation of the wrapped object, typically a string
    def render(view: nil, **options, &block)
      previous_view = @view
      rendered = nil
      captured = ''

      begin
        @view = view unless view.nil?
        raise Kadmin::Presenter::NoViewContext if @view.nil?
        captured = capture(&block) if block_given?
        rendered = generate(captured, **options)
      ensure
        @view = previous_view
      end

      return rendered
    end

    # Generates the representation of the wrapped object.
    # Should be overloaded and implemented by a concrete class.
    def generate(captured, **)
      return "<div>#{__getobj__.inspect}#{captured}</div>".html_safe
    end
    protected :generate

    class NoViewContext < Kadmin::Error
      def initialize(message = nil)
        message ||= 'cannot render without a view context'
        super(message)
      end
    end
  end
end

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
kadmin-0.7.0 lib/kadmin/presenter.rb
kadmin-0.6.21 lib/kadmin/presenter.rb
kadmin-0.6.19 lib/kadmin/presenter.rb
kadmin-0.6.18 lib/kadmin/presenter.rb
kadmin-0.6.17 lib/kadmin/presenter.rb
kadmin-0.6.16 lib/kadmin/presenter.rb
kadmin-0.6.13 lib/kadmin/presenter.rb
kadmin-0.6.12 lib/kadmin/presenter.rb
kadmin-0.6.11 lib/kadmin/presenter.rb
kadmin-0.6.10 lib/kadmin/presenter.rb
kadmin-0.6.9 lib/kadmin/presenter.rb
kadmin-0.6.8 lib/kadmin/presenter.rb
kadmin-0.6.7 lib/kadmin/presenter.rb
kadmin-0.6.6 lib/kadmin/presenter.rb
kadmin-0.6.5 lib/kadmin/presenter.rb
kadmin-0.6.4 lib/kadmin/presenter.rb
kadmin-0.6.3 lib/kadmin/presenter.rb
kadmin-0.6.1 lib/kadmin/presenter.rb
kadmin-0.5.7 lib/kadmin/presenter.rb
kadmin-0.5.6 lib/kadmin/presenter.rb