Sha256: 49237e144b6cb87ba911df7a402536b9ab97a09f2b33058f9baccc4905842855

Contents?: true

Size: 1 KB

Versions: 6

Compression:

Stored size: 1 KB

Contents

# frozen_string_literal: true

module ::AmberComponent
  # Contains the content and type of an asset.
  class TypedContent
    class << self
      # @param val [Hash, self]
      # @return [self]
      def wrap(val)
        return val if val.is_a?(self)

        raise InvalidTypeError, <<~MSG unless val.respond_to?(:[])
          `TypedContent` should be a `Hash` or `#{self}` but was `#{val.class}` (#{val.inspect})
        MSG

        new(type: val[:type], content: val[:content])
      end

      alias [] wrap
    end

    # @param type [Symbol, String, nil]
    # @param content [String, Proc, nil]
    def initialize(type:, content:)
      @type = type&.to_sym
      @content = content
      freeze
    end

    # @return [Symbol, nil]
    attr_reader :type
    # @return [String, Proc, nil]
    attr_reader :content

    # Stringified content.
    #
    # @return [String]
    def to_s
      return @content.call.to_s if @content.is_a?(::Proc)

      @content.to_s
    end

    alias string_content to_s
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
amber_component-1.2.0 lib/amber_component/typed_content.rb
amber_component-1.1.1 lib/amber_component/typed_content.rb
amber_component-1.1.0 lib/amber_component/typed_content.rb
amber_component-1.0.0 lib/amber_component/typed_content.rb
amber_component-0.0.5 lib/amber_component/typed_content.rb
amber_component-0.0.4 lib/amber_component/typed_content.rb