Sha256: 7190334165ad01b519b554029c4a43c7cbed67225a8d2a7b72d7d0dd171d3f4e

Contents?: true

Size: 1.36 KB

Versions: 9

Compression:

Stored size: 1.36 KB

Contents

module FactoryBurgers
  # Module for adding, finding, and using application data presenters. Presenters
  # are used to define what attributes to show in the front end, what to call the
  # built objects, and managing links to the objects in the application if they
  # exist.
  module Presenters
    @presenters = {}

    module_function

    def present(klass, with: nil, &blk)
      raise ArgumentError, "Provide `with` or block, but not both" if with && blk

      presenter = with || build_presenter(klass, &blk)
      @presenters[klass.to_s] = presenter
    end

    def purge!
      @links = {}
      @presenters = {}
    end

    def presenter_for(object)
      presenter_class_for(object).new(object)
    end

    def presenter_class_for(object)
      matching_class = object.class.ancestors.map(&:name).find do |class_name|
        @presenters.key?(class_name)
      end

      return matching_class ? @presenters[matching_class] : FactoryBurgers::Presenters::Base
    end

    # TODO: use this from FactoryOutput
    def data_for(object)
      presenter = presenter_for(object) or return nil
      {
        type: presenter.type,
        attributes: presenter.attributes,
        link: presenter.link_path,
      }
    end

    # block provided to `present`; build a presenter class
    def build_presenter(klass, &blk)
      PresenterBuilder.new(klass).build(&blk)
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
factory_burgers-1.1.3 lib/factory_burgers/presenters.rb
factory_burgers-1.1.2 lib/factory_burgers/presenters.rb
factory_burgers-1.1.1 lib/factory_burgers/presenters.rb
factory_burgers-1.1.0 lib/factory_burgers/presenters.rb
factory_burgers-1.0.0 lib/factory_burgers/presenters.rb
factory_burgers-0.1.5 lib/factory_burgers/presenters.rb
factory_burgers-0.1.4 lib/factory_burgers/presenters.rb
factory_burgers-0.1.2 lib/factory_burgers/presenters.rb
factory_burgers-0.1.0 lib/factory_burgers/presenters.rb