Class: Jsapi::Meta::Pathname

Inherits:
Object
  • Object
show all
Defined in:
lib/jsapi/meta/pathname.rb

Overview

Represents a relative path name.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*segments) ⇒ Pathname

:nodoc:



21
22
23
24
25
26
# File 'lib/jsapi/meta/pathname.rb', line 21

def initialize(*segments) # :nodoc:
  @segments = segments.flat_map do |segment|
    segment = segment.to_s.delete_prefix('/')
    segment.present? ? segment.split('/', -1) : ''
  end
end

Instance Attribute Details

#segmentsObject (readonly)

Returns the value of attribute segments.



17
18
19
# File 'lib/jsapi/meta/pathname.rb', line 17

def segments
  @segments
end

Class Method Details

.from(name) ⇒ Object

Transforms name to an instance of this class.



9
10
11
12
13
14
# File 'lib/jsapi/meta/pathname.rb', line 9

def from(name)
  return name if name.is_a?(Pathname)

  name = name[1..].presence if name&.match?(%r{\A/+\z})
  name.nil? ? new : new(name)
end

Instance Method Details

#+(other) ⇒ Object

Creates a new Pathname by appending other to itself. Returns itself if other is nil.



36
37
38
39
40
# File 'lib/jsapi/meta/pathname.rb', line 36

def +(other)
  return self if other.nil?

  Pathname.new(*@segments, *Pathname.from(other).segments)
end

#==(other) ⇒ Object Also known as: eql?

:nodoc:



28
29
30
# File 'lib/jsapi/meta/pathname.rb', line 28

def ==(other) # :nodoc:
  other.is_a?(Pathname) && segments == other.segments
end

#ancestorsObject

Returns an array containing itself and all parent pathnames.



43
44
45
46
47
# File 'lib/jsapi/meta/pathname.rb', line 43

def ancestors
  @ancestors ||= @segments.count.downto(0).map do |i|
    Pathname.new(*@segments[0, i])
  end
end

#inspectObject

:nodoc:



49
50
51
# File 'lib/jsapi/meta/pathname.rb', line 49

def inspect # :nodoc:
  "#<#{self.class} #{to_s.inspect}>"
end

#to_sObject Also known as: as_json

Returns the relative path name as a string.



54
55
56
57
58
# File 'lib/jsapi/meta/pathname.rb', line 54

def to_s
  @to_s ||= @segments.presence&.each_with_index&.map do |segment, index|
    index.zero? && segment.blank? ? '//' : "/#{segment}"
  end&.join || '/'
end