Sha256: 8c397d0b63381c36ade5ca976255127bb611aa1bc5e0d3c290c24b59364e4f2e

Contents?: true

Size: 1.36 KB

Versions: 4

Compression:

Stored size: 1.36 KB

Contents

# frozen_string_literal: true

require 'media_types/object'

module MediaTypes
  class Formatter < DelegateClass(Hash)

    class << self
      def call(*args, **options)
        new(*args, **options).call
      end
    end

    def call
      filtered_arguments = arguments
      return template if MediaTypes::Object.new(filtered_arguments).empty?

      format(rework_template(filtered_arguments), filtered_arguments)
    end

    private

    def template
      fetch(:format)
    end

    def rework_template(filtered_arguments)
      filtered_arguments.reduce(template) do |reworked, (key, value)|
        next reworked if MediaTypes::Object.new(value).present?
        start_of_template_variable = "%<#{key}>"

        # noinspection RubyBlockToMethodReference
        reworked.gsub("[\\.+](#{start_of_template_variable})") { start_of_template_variable }
      end
    end

    def format_view(view)
      MediaTypes::Object.new(view).present? && ".#{view}" || ''
    end

    def arguments
      # noinspection RubyBlockToMethodReference
      {
        version: self[:version],
        suffix: self[:suffix],
        type: self[:type],
        view: self[:view]
      }.select { |argument,| argument_present?(argument) }
    end

    def argument_present?(argument)
      template.include?("%<#{argument}>")
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
media_types-0.5.3 lib/media_types/formatter.rb
media_types-0.5.2 lib/media_types/formatter.rb
media_types-0.5.1 lib/media_types/formatter.rb
media_types-0.5.0 lib/media_types/formatter.rb