spec
require 'spec_helper'
describe Pyramid::PathInterpolater do
it 'replaces parts with corresponding value' do
result = described_class.('entities/:entity_id', {entity_id: '1'})
expect(result).to eq('entities/1')
result = described_class.('entities/:entity_id/items/:item_id', {entity_id: '1', item_id: '2'})
expect(result).to eq('entities/1/items/2')
end
it 'uses a interpolater with path' do
m = described_class.new('entities/:entity_id')
result = m.(entity_id: '1')
expect(result).to eq('entities/1')
end
it 'returns nil if path is nil' do
m = described_class.new(nil)
result = m.(entity_id: '1')
expect(result).to be_nil
end
end
implementations:
module Pyramid
module PathInterpolater
REGEXP = /:\w+/
def self.call(path, params)
return nil unless path
matches = path.scan REGEXP
result = path.dup
matches.each do |m|
m = m[1..-1].to_sym
result = result.sub(REGEXP, params[m].to_s)
end
result
end
def self.new(path)
method(:call).curry[path]
end
end
end
module Pyramid
class PathInterpolater
REGEXP = /:\w+/
def self.call(path, params)
new(path).call(params)
end
def call(params)
return nil unless path
matches = path.scan REGEXP
result = path.dup
matches.each do |m|
m = m[1..-1].to_sym
result = result.sub(REGEXP, params[m].to_s)
end
result
end
def initialize(path)
@path = path
end
private
attr_accessor :path
end
end