Class: Iriq::PathShape

Inherits:
Object
  • Object
show all
Defined in:
lib/iriq/path_shape.rb

Overview

Converts a sequence of path segments into a route-shape string by replacing variable segments with ‘type` placeholders.

PathShape.for(["users", "123", "orders", "456"])
# => "/users/{integer_id}/orders/{integer_id}"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(classifier: SegmentClassifier.new) ⇒ PathShape

Returns a new instance of PathShape.



8
9
10
# File 'lib/iriq/path_shape.rb', line 8

def initialize(classifier: SegmentClassifier.new)
  @classifier = classifier
end

Class Method Details

.for(segments, classifier: SegmentClassifier.new) ⇒ Object



23
24
25
# File 'lib/iriq/path_shape.rb', line 23

def self.for(segments, classifier: SegmentClassifier.new)
  new(classifier: classifier).for(segments)
end

Instance Method Details

#for(segments) ⇒ Object



12
13
14
15
16
# File 'lib/iriq/path_shape.rb', line 12

def for(segments)
  return "/" if segments.nil? || segments.empty?

  "/" + segments.map { |s| shape_segment(s) }.join("/")
end

#shape_segment(segment) ⇒ Object



18
19
20
21
# File 'lib/iriq/path_shape.rb', line 18

def shape_segment(segment)
  type = @classifier.classify(segment)
  @classifier.variable?(type) ? "{#{type}}" : segment
end