Sha256: 479ab513caf9ba3036d3c78e8ddc3296a5983a39da10ab656a42ddda245e341c

Contents?: true

Size: 1.18 KB

Versions: 1

Compression:

Stored size: 1.18 KB

Contents

require 'uri_template'

module Spyke
  class InvalidPathError < StandardError; end
  class Path

    def initialize(pattern, params = {})
      @pattern = pattern
      @params = params.symbolize_keys
    end

    def join(other_path)
      self.class.new File.join(path, other_path.to_s), @params
    end

    def to_s
      path
    end

    def variables
      @variables ||= uri_template.variables.map(&:to_sym)
    end

    private

      def uri_template
        @uri_template ||= URITemplate.new(:colon, pattern_with_rfc_style_parens)
      end

      def pattern_with_rfc_style_parens
        @pattern.gsub('(', '{').gsub(')', '}')
      end

      def path
        validate_required_params!
        uri_template.expand(@params).chomp('/')
      end

      def validate_required_params!
        if missing_required_params.any?
          raise Spyke::InvalidPathError, "Missing required params: #{missing_required_params.join(', ')} in #{@pattern}. Mark optional params with parens eg: (:param)"
        end
      end

      def missing_required_params
        required_params - @params.keys
      end

      def required_params
        @pattern.scan(/\/:(\w+)/).flatten.map(&:to_sym)
      end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
spyke-1.7.0 lib/spyke/path.rb