Skip to content

Instantly share code, notes, and snippets.

@he9lin
Last active August 29, 2015 14:19
Show Gist options
  • Save he9lin/b104a588dd788adc5991 to your computer and use it in GitHub Desktop.
Save he9lin/b104a588dd788adc5991 to your computer and use it in GitHub Desktop.
Fun with curry

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment