Sha256: 1ed0b406e593df16d9e9e6c942d09bc105bf38c3893031c7d4fc29ba3d7d19fd

Contents?: true

Size: 1.45 KB

Versions: 1

Compression:

Stored size: 1.45 KB

Contents

require 'rest-client'
require 'json'
require 'gnip-rule/rule'

module GnipRule
  class Client
    attr_reader :url, :username, :password

    def initialize(url, username, password)
      @url = url.gsub(/\.xml$/, '.json')
      @username = username
      @password = password
    end

    def add(input, tag=nil)
      post(@url, gen_json_payload(input, tag))
    end

    def delete(input, tag=nil)
      post("#@url?_method=delete", gen_json_payload(input, tag))
    end

    def list()
      response = RestClient::Request.new(:method => :get, :url => @url,
                                         :user => @username, :password => @password,
                                         :headers => { :accept => :json }).execute
      JSON.parse(response.to_s)['rules'].collect { |o| Rule.new(o['value'], o['tag']) }
    end

    def gen_json_payload(input, tag=nil)
      input = [input] unless input.respond_to? :collect
      rules = input.map { |i|
        if i.respond_to?(:to_rule)
          i.to_rule(tag)
        elsif i.is_a?(String)
          GnipRule::Rule.new(i, tag)
        else
          raise 'Input must be convertable to GnipRule::Rule'
        end
      }
      { rules: rules.map(&:to_hash) }.to_json
    end

    protected
    def post(url, data)
      RestClient::Request.new(:method => :post, :url => url, :payload => data,
          :user => @username, :password => @password, :headers => { :content_type => :json, :accept => :json }).execute
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
gnip-rule-1.0.0 lib/gnip-rule/client.rb