Class: Hanami::Utils::PathPrefix

Inherits:
Object
  • Object
show all
Defined in:
gems/gems/hanami-utils-2.2.0.beta1/lib/hanami/utils/path_prefix.rb

Overview

Prefixed string

Since:

  • 0.1.0

Instance Method Summary collapse

Constructor Details

#initialize(string = nil, separator = DEFAULT_SEPARATOR) ⇒ PathPrefix

Initialize the path prefix

Parameters:

  • string (::String) (defaults to: nil)

    the prefix value

  • separator (::String) (defaults to: DEFAULT_SEPARATOR)

    the separator used between tokens

See Also:

Since:

  • 0.1.0

def initialize(string = nil, separator = DEFAULT_SEPARATOR)
  @string = string.to_s
  @separator = separator
end

Instance Method Details

#==(other) ⇒ TrueClass, FalseClass Also known as: eql?

Equality

Returns:

  • (TrueClass, FalseClass)

Since:

  • 0.3.0

def ==(other)
  to_s == other
end

#hashInteger

Returns the hash of the internal string

Returns:

  • (Integer)

Since:

  • 0.3.0

def hash
  @string.hash
end

#join(*strings) ⇒ Hanami::Utils::PathPrefix

Joins self with the given token. It cleans up all the separator repetitions.

Examples:

Single string

require 'hanami/utils/path_prefix'

path_prefix = Hanami::Utils::PathPrefix.new('/posts')
path_prefix.join('new').to_s  # => "/posts/new"
path_prefix.join('/new').to_s # => "/posts/new"

path_prefix = Hanami::Utils::PathPrefix.new('posts')
path_prefix.join('new').to_s  # => "/posts/new"
path_prefix.join('/new').to_s # => "/posts/new"

Multiple strings

require 'hanami/utils/path_prefix'

path_prefix = Hanami::Utils::PathPrefix.new('myapp')
path_prefix.join('/assets', 'application.js').to_s
  # => "/myapp/assets/application.js"

Parameters:

  • strings (::String)

    the token(s) we want to join

Returns:

Since:

  • 0.1.0

def join(*strings)
  relative_join(strings).absolute!
end

#relative_join(strings, separator = @separator) ⇒ Hanami::Utils::PathPrefix

Joins self with the given token, without prefixing it with separator. It cleans up all the separator repetitions.

Examples:

require 'hanami/utils/path_prefix'

path_prefix = Hanami::Utils::PathPrefix.new 'posts'
path_prefix.relative_join('new').to_s      # => 'posts/new'
path_prefix.relative_join('new', '_').to_s # => 'posts_new'

Parameters:

  • strings (::String)

    the tokens we want to join

  • separator (::String) (defaults to: @separator)

    the separator used between tokens

Returns:

Raises:

  • (TypeError)

    if one of the argument can’t be treated as a string

Since:

  • 0.1.0

def relative_join(strings, separator = @separator)
  raise TypeError if separator.nil?

  prefix = @string.gsub(@separator, separator)
  result = [prefix, strings]
  result.flatten!
  result.compact!
  result.reject! { |string| string == separator }

  self.class.new(
    result.join(separator), separator
  ).relative!
end

#to_s::String Also known as: to_str

Returns a string representation

Returns:

Since:

  • 0.3.0

def to_s
  @string
end