Sha256: 14fbb3710a3146f9cc2aac61f9637cca81c85360580084e95558701468edb60b

Contents?: true

Size: 1.1 KB

Versions: 5

Compression:

Stored size: 1.1 KB

Contents

module Shogun
  module Presenter
    def initialize(resource:, meta: {}, links: {}, linked: {})
      @source = resource
      @meta = meta
      @links = links
      @linked = linked
    end

    def href
      [host, namespace, id].join("/")
    end

    def meta
      @meta
    end

    def linked
      @linked
    end

    def links
      @links.tap do |hash|
        associations.each do |name|
          case association(name).macro
          when :has_many
            hash.store(name, source.public_send(name).pluck(:id))
          when :belongs_to
            hash.store(name, source.public_send(association(name).foreign_key))
          when :has_one
            hash.store(name, source.public_send(name).pluck(:id))
          end
        end
      end
    end

    private def host
      ENV["API_HOST"]
    end

    private def associations
      self.class.const_get("ASSOCIATIONS")
    end

    private def namespace
      self.class.const_get("NAMESPACE")
    end

    private def association(name)
      source.class.reflections[name.to_sym]
    end

    private def source
      @source
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
shogun-3.0.0 lib/shogun/presenter.rb
shogun-2.1.1 lib/shogun/presenter.rb
shogun-2.1.0 lib/shogun/presenter.rb
shogun-2.0.0 lib/shogun/presenter.rb
shogun-1.0.0 lib/shogun/presenter.rb