Sha256: fd0bbb0e6bd6c93ed3492937f399859204ba7706b053f806a26bcf5ec84b6db6

Contents?: true

Size: 1.45 KB

Versions: 2

Compression:

Stored size: 1.45 KB

Contents

require 'uri'

module Commute
  module Extension

    # The url extensions provides an `url` method that pushes
    # a transformation on the context that renders the required url
    # based on a pattern.
    #
    # The pattern uses the standard ruby format specification. When
    # not all variables are present, the url in sanitized in a
    # way that it is valid again.
    #
    # Examples:
    #
    #   class GistApi < Commute::Api
    #     include Commute::Extension::Url
    #
    #     url 'https://api.github.com/gists/%{filter}'
    #
    #     def user user = nil
    #       with(user: user)
    #       url('https://api.github.com/user/%{user}/gists').all
    #     end
    #   end
    #
    module Url
      METHODS = [:url].freeze

      # Public: Define the url pattern to use.
      #
      # pattern - The patter with variables between %{}.
      #
      # Returns self.
      def url pattern
        # Transform the context, filling in the url.
        transform do |request, context|
          # First, render the url pattern.
          rendered = pattern.gsub(/%{([^}]*)}/) { |m| context[$1.to_sym] }
          # Parse the rendered url using uri.
          uri = URI rendered
          # Substitute multiple / by one /.
          uri.path.gsub! /\/+/, '/'
          # Substiture /.format by .format
          uri.path.sub! /\/\.([^\/]+)$/, '.\1'

          # Assign the uri to the request.
          request.uri = uri
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
commute-0.3.0.pre.2 lib/commute/extensions/url.rb
commute-0.3.0.pre lib/commute/extensions/url.rb