Sha256: 11094396db9317036b9c1c275d3d275c05e3b12af249951e0c714df07056d402

Contents?: true

Size: 1.98 KB

Versions: 11

Compression:

Stored size: 1.98 KB

Contents

# frozen_string_literal: true

require 'eac_ruby_utils/core_ext'

module Avm
  module Entries
    class UriBuilder
      require_sub __FILE__

      FIELDS = %w[scheme user password host port path query fragment].freeze
      FIELDS_TRANSLATIONS = {
        username: :user, hostname: :host
      }.freeze
      ENTRIES_FIELDS = FIELDS.map do |field|
        FIELDS_TRANSLATIONS.key(field.to_sym).if_present(field).to_s
      end

      class << self
        def from_all_fields(&block)
          r = new
          ENTRIES_FIELDS.each do |field_name|
            field_value = block.call(field_name)
            r.field_set(field_name, field_value) if field_value.present?
          end
          r
        end

        def from_source(source)
          if source.is_a?(::Addressable::URI)
            from_source_uri(source)
          elsif source.blank?
            new
          else
            raise "Unexpected source: #{source}"
          end
        end

        def from_source_uri(source_uri)
          new(source_uri.to_hash)
        end
      end

      common_constructor :data, default: [{}]

      def field_get(name)
        data[name.to_sym].if_present(&:to_s)
      end

      def field_set(field, value)
        tfield = translate_field(field)
        if FIELDS.include?(tfield)
          main_field_set(tfield, value)
        else
          sub_field_set(tfield, value)
        end
      end

      def translate_field(field)
        if FIELDS_TRANSLATIONS.key?(field.to_sym)
          FIELDS_TRANSLATIONS.fetch(field.to_sym).to_s
        else
          field.to_s
        end
      end

      # @return [Addressable::URI, nil]
      def to_uri
        to_required_uri
      rescue ::Addressable::URI::InvalidURIError
        nil
      end

      # @return [Addressable::URI]
      def to_required_uri
        ::Addressable::URI.new(FIELDS.map { |f| [f.to_sym, field_get(f)] }.to_h)
      end

      private

      def main_field_set(name, value)
        data[name.to_sym] = value
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 2 rubygems

Version Path
avm-0.37.0 lib/avm/entries/uri_builder.rb
eac_tools-0.24.0 sub/avm/lib/avm/entries/uri_builder.rb
avm-0.36.0 lib/avm/entries/uri_builder.rb
eac_tools-0.23.0 sub/avm/lib/avm/entries/uri_builder.rb
avm-0.35.1 lib/avm/entries/uri_builder.rb
eac_tools-0.22.0 sub/avm/lib/avm/entries/uri_builder.rb
eac_tools-0.21.0 sub/avm/lib/avm/entries/uri_builder.rb
eac_tools-0.20.0 sub/avm/lib/avm/entries/uri_builder.rb
eac_tools-0.19.0 sub/avm/lib/avm/entries/uri_builder.rb
avm-0.35.0 lib/avm/entries/uri_builder.rb
eac_tools-0.18.0 sub/avm/lib/avm/entries/uri_builder.rb