Sha256: 2491ad022d92eb3643494fbd6a786a8f52d31c794bcd162762f88ce61f2a9736

Contents?: true

Size: 960 Bytes

Versions: 1

Compression:

Stored size: 960 Bytes

Contents

module Trav3
  class Options
    def initialize(**args)
      build(**args)
    end

    def opts
      if @opts.empty?
        ''
      else
        "?#{@opts.join('&')}"
      end
    end

    def build(**args)
      @opts ||= []

      args.each do |(key, value)|
        remove(key)
        @opts.push("#{key}=#{value}")
      end

      self
    end

    def remove(key)
      return_value = nil

      @opts = @opts.delete_if do |item|
        head, tail = split.call item

        return_value = tail if head == key.to_s
      end

      return_value
    end

    def reset!
      @opts = []
    end

    def +(other)
      raise TypeError, "Options type expected, #{other.class} given" unless other.is_a? Options

      @opts += other.instance_variable_get(:@opts)

      self
    end

    def to_s
      opts
    end

    def to_h
      @opts.map(&split).to_h
    end

    private

    def split
      ->(entry) { entry.split('=') }
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
trav3-0.2.2 lib/trav3/options.rb