Sha256: 6902fc03e97d42c45b4f44d0693d8f1422860df2a5f61e07ee2d092a256d92ea

Contents?: true

Size: 1.66 KB

Versions: 7

Compression:

Stored size: 1.66 KB

Contents

require 'rake/tasklib'


module Pact

  ##
  # To enable `rake pact`, put something like this in your Rakefile:
  #
  #     ```
  #     require 'pact/rake_task'
  #
  #     Pact::RakeTask.new do |pact|
  #       pact.file 'spec/pacts/some-pact.json',
  #         from_url: 'http://example.com/some-pact.json'
  #       pact.file 'spec/pacts/other-pact.json',
  #         from_url: 'http://example.com/other-pact.json'
  #     end
  #     ```
  class RakeTask < ::Rake::TaskLib
    attr_reader :connections

    def initialize(name = :pact)
      @connections = []

      yield self

      namespace name do
        desc "Update integration pacts from external sources"
        task :pull do
          connections.each do |conn|
            body = fetch conn[:url]
            File.open(conn[:file], 'w') {|f| f.write body }
            puts "Wrote #{conn[:url]} to #{conn[:file]}"
          end
        end
      end
      task name => "#{name}:pull" # default task for the namespace
    end

    def file(filename, options = {})
      url = options.fetch(:from_url)
      @connections << {file: filename, url: url}
    end

    private
    # written with plain Net::HTTP to avoid bringing in extra dependencies
    def fetch(url_string, redirection_limit = 5)
      raise 'Too many HTTP redirects' if redirection_limit == 0
      url = URI.parse(url_string)
      response = Net::HTTP.get_response(url)
      case response
      when Net::HTTPSuccess then
        response.body
      when Net::HTTPRedirection then
        location = response['Location']
        fetch(location, redirection_limit - 1)
      else
        response.value # raise the appropriate error
      end
    end
  end


end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
pact-1.0.3 lib/pact/rake_task.rb
pact-1.0.2 lib/pact/rake_task.rb
pact-1.0.1 lib/pact/rake_task.rb
pact-1.0.0 lib/pact/rake_task.rb
pact-0.1.37 lib/pact/rake_task.rb
pact-0.1.35 lib/pact/rake_task.rb
pact-0.1.28 lib/pact/rake_task.rb