Sha256: 2e584a5e2324f5639240f3ed29d8e41bcb5cb0c3ad5d1ad7390e34a0fda6a028

Contents?: true

Size: 1.53 KB

Versions: 1

Compression:

Stored size: 1.53 KB

Contents

class Newslettre::API
  attr_accessor :email, :password, :format, :url

  def initialize options = {}
    @url = "https://sendgrid.com/api/newsletter"
    @email = options.delete :email
    @password = options.delete :password
    @format = :json
  end

  def authenticated?
    not email.nil? and not password.nil?
  end

  %w{get list add delete edit}.each do |m|
    define_method m do |*args|
      raise NotAuthenticatedFailure unless authenticated?
      params, options = args
      params ||= {}
      options ||= {}

      response, status = request url_for(m, options), params

      raise ClientFailure if status > 399 and status < 500
      raise EndpointFailure if status > 499

      respond response
    end
  end

  alias_method :post, :add
  alias_method :put, :edit

  class NotAuthenticatedFailure < StandardError; end
  class ClientFailure < StandardError; end
  class EndpointFailure < StandardError; end

  protected

  def credentials
    {
      :api_user => email,
      :api_key => password
    }
  end

  def request address, params
    fields =  params.merge(credentials).map { |key, value|
      if value.kind_of? Array
        value.map {|v| Curl::PostField.content("#{key}[]", v.to_s) }
      else
        Curl::PostField.content(key.to_s, value.to_s)
      end
    }.flatten

    curl = Curl::Easy.new address

    curl.http_post(*fields)

    [curl, curl.response_code]
  end

  def respond response
    JSON.load response.body_str
  end

  def url_for path, options = {}
    "#{url}#{options[:prefix]}/#{path}.#{format}"
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
newslettre-0.1.1 lib/newslettre/api.rb