Permalink
Browse files

Commit migration from old zapt_in gem

  • Loading branch information...
1 parent 690f489 commit f59e04ef0e32b11385d2836380dc5ea0cf4cada9 Roger Leite committed Feb 16, 2012
View
@@ -0,0 +1,7 @@
+pkg/*
+*.gem
+.bundle
+doc/*
+test.rb
+.rvmrc
+tags
View
@@ -0,0 +1,4 @@
+source "http://rubygems.org"
+
+# Specify your gem's dependencies in zapt_in.gemspec
+gemspec
View
20 LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2011 Roger Leite
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+'Software'), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
View
1 README
@@ -1 +0,0 @@
-Ruby gem to help use abr.io
View
@@ -0,0 +1,70 @@
+Abrio
+======
+
+A Ruby API for http://abr.io
+
+More information for API here:
+http://abr.io/pages/api
+
+Project goals:
+ *Easy to use
+ *Flexible to configure
+ *No external dependencies
+
+Installation
+------------
+
+ gem install abrio
+
+Usage
+-----
+
+Case 1:
+
+ require "rubygems"
+ require "abrio"
+
+ client = Abrio::Client.new(:login => "login", :key => "Z_123")
+ url = client.shorten("http://google.com")
+ url.short_url #=> "http://abr.io/11jU"
+
+Case 2:
+
+ require "rubygems"
+ require "abrio"
+
+ #This is useful to setup config at Rails initializer for example.
+ Abrio.setup do |client|
+ client.uri = "http://abr.io/api/links"
+ client.login = "login"
+ client.key = "key"
+ end
+ url = Abrio.shorten("http://google.com")
+ url.short_url #=> "http://abr.io/18VN"
+
+Running the Tests
+-----------------
+
+Install development dependencies with:
+
+ $ bundle install
+
+To run the test suite:
+
+ $ rake test
+
+
+Contributing
+------------
+
+Once you've made your great commits:
+
+1. [Fork][0] abrio
+2. Create a topic branch - `git checkout -b my_branch`
+3. Push to your branch - `git push origin my_branch`
+4. Create an [Issue][1] with a link to your branch
+5. That's it!
+
+
+[0]: http://help.github.com/forking/
+[1]: https://github.com/abril/abrio/issues
View
@@ -0,0 +1,27 @@
+require 'rake'
+require 'rake/testtask'
+require 'rake/rdoctask'
+require 'bundler'
+
+Bundler::GemHelper.install_tasks
+
+desc 'Generate API documentation to doc/rdocs/index.html'
+Rake::RDocTask.new do |rd|
+ rd.rdoc_dir = 'doc'
+ rd.main = 'README.md'
+ rd.rdoc_files.include "README.md", "LICENSE", "lib/**/*\.rb"
+
+ rd.options << '--inline-source'
+ rd.options << '--line-numbers'
+ rd.options << '--all'
+ rd.options << '--fileboxes'
+end
+
+desc "Run tests"
+Rake::TestTask.new do |t|
+ t.libs << "test"
+ t.test_files = FileList['test/**/*.rb']
+ t.verbose = true
+end
+
+task :default => :test
View
@@ -0,0 +1,25 @@
+# -*- encoding: utf-8 -*-
+$:.push File.expand_path("../lib", __FILE__)
+require "abrio/version"
+
+Gem::Specification.new do |s|
+ s.name = "abrio"
+ s.version = Abrio::VERSION
+ s.platform = Gem::Platform::RUBY
+ s.authors = ["Roger Leite"]
+ s.email = ["roger.leite@abril.com.br"]
+ s.homepage = ""
+ s.summary = %q{Client ruby para o encurtador http://abr.io}
+ s.description = %q{Client ruby para o encurtador http://abr.io}
+ s.required_ruby_version = ">= 1.8.7"
+
+ #s.rubyforge_project = "abrio"
+ s.add_development_dependency "turn", "~> 0.8.2"
+ s.add_development_dependency "fakeweb", "~> 1.3.0"
+ s.add_development_dependency "mocha", "~> 0.9.12"
+
+ s.files = `git ls-files`.split("\n")
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
+ s.require_paths = ["lib"]
+end
View
@@ -0,0 +1,31 @@
+module Abrio
+ autoload :Client, "abrio/client"
+ autoload :Request, "abrio/request"
+ autoload :Url, "abrio/url"
+ autoload :Error, "abrio/error"
+
+ # Useful to set Abrio client parameters.
+ #
+ # Abrio.setup do |client|
+ # client.uri = "http://abr.io/api/links"
+ # client.login = "login"
+ # client.key = "key"
+ # end
+ #
+ def self.setup
+ yield(client) if block_given?
+ end
+
+ # Shortcut to Abrio::Client.shorten
+ def self.shorten(long_url, options = {})
+ client.shorten(long_url, options)
+ end
+
+ protected
+
+ #Returns Abrio::Client instance
+ def self.client
+ @@client ||= Client.new
+ end
+
+end
View
@@ -0,0 +1,40 @@
+#Client proxy for Abr.io API.
+class Abrio::Client
+
+ attr_accessor :uri, :login, :key
+
+ DEFAULT_PARAMS = {:format => "xml", :version => "1.0"}
+
+ #Use the following options to initialize your client:
+ # [uri] - Default: "abr.io/api/links"
+ # [login] - Your login from Zapt.In. See: http://abr.io/pages/api
+ # [key] - Your key from Zapt.In. See: http://abr.io/pages/api
+ def initialize(options = {})
+ @uri = options[:uri] || "http://abr.io/api/links"
+ @login = options[:login]
+ @key = options[:key]
+ end
+
+ #Shorten an url.
+ #[long_url] url you want to shorten.
+ #[options] Optional Hash. You can pass the following keys:
+ # [uri] - Default: "abr.io/api/links"
+ # [login] - Your login from Zapt.In. See: http://abr.io/pages/api
+ # [key] - Your key from Zapt.In. See: http://abr.io/pages/api
+ def shorten(long_url, options = {})
+ return nil if long_url.nil? || long_url == ""
+
+ @uri = options.delete(:uri) || @uri
+ params = {:login => options.delete(:login) || @login,
+ :key => options.delete(:key) || @key}.merge(DEFAULT_PARAMS)
+ params[:longUrl] = long_url
+
+ begin
+ response = Abrio::Request.get("#{self.uri}/shorten", params)
+ Abrio::Url.parse(response)
+ rescue Abrio::Error => e
+ Abrio::Url.new(:status_code => "ERROR", :errorMessage => e.message, :error_code => -1)
+ end
+ end
+
+end
View
@@ -0,0 +1,2 @@
+class Abrio::Error < StandardError
+end
View
@@ -0,0 +1,38 @@
+require "net/http"
+require "uri"
+
+#Wrapper responsible for all requests.
+class Abrio::Request
+
+ #Call get at *uri* with *parameters*.
+ #[uri] Complete url. Example: http://abr.io/api/links/shorten
+ #[parameters] Hash of parameters. Example: {:format => "xml", :version => "1.0"}
+ #
+ #Returns response body, a String.
+ def self.get(uri, parameters)
+ params = build_parameters(parameters)
+
+ begin
+ url = URI.parse(uri)
+ req = Net::HTTP::Get.new("#{url}?#{params}")
+ res = Net::HTTP.start(url.host, url.port) do |http|
+ http.request(req)
+ end
+ res.body
+ rescue StandardError => e
+ raise Abrio::Error.new(e)
+ end
+ end
+
+ private
+
+ #Receives a Hash.
+ #
+ #Returns a String in format: "key=value&key2=value2"
+ def self.build_parameters(params)
+ array_params = []
+ params.each_pair { |key, value| array_params << "#{key}=#{value}"}
+ array_params.join("&")
+ end
+
+end
View
@@ -0,0 +1,39 @@
+require 'rexml/document'
+
+#Represents Abrio API response.
+class Abrio::Url
+
+ attr_reader :status_code, :error_message, :error_code
+ attr_reader :short_url
+
+ #Initialize all read-only atributes with Hash.
+ def initialize(attrs = {})
+ attrs.each_pair do |attr, value|
+ self.instance_variable_set("@#{attr}", value)
+ end
+ end
+
+ #Parses *xml* from Abrio API.
+ #
+ #See documentation at http://abr.io/pages/api
+ def self.parse(xml_body)
+ validates_xml(xml_body)
+
+ doc = REXML::Document.new(xml_body)
+
+ attributes = {:status_code => doc.elements["*/statusCode"].text,
+ :error_message => doc.elements["*/errorMessage"].text,
+ :error_code => doc.elements["*/errorCode"].text}
+
+ if (result = doc.elements["*/results/nodeKeyVal"])
+ attributes.merge!({:short_url => result.elements["shortUrl"].text})
+ end
+ self.new(attributes)
+ end
+
+ def self.validates_xml(xml)
+ raise Abrio::Error.new("XML body cannot be blank") if xml.nil? || xml.empty?
+ raise Abrio::Error.new("Does not appear to be a valid Abrio XML.\n\n#{xml}") unless xml.start_with?("<abrio>")
+ end
+
+end
View
@@ -0,0 +1,3 @@
+module Abrio
+ VERSION = "0.0.5"
+end
View
@@ -0,0 +1,63 @@
+require 'test_helper'
+
+class Abrio::ClientTest < Test::Unit::TestCase
+
+ include Abrio::Fixtures::XmlResponse
+ DEFAULT_EXPECTED_PARAMS = {:longUrl => 'http://google.com', :version => '1.0', :format => 'xml', :key => 'Z_VALID', :login => 'rogleite'}
+
+ def test_default_configurations
+ assert_equal "http://abr.io/api/links", Abrio::Client.new.uri
+ end
+
+ def test_shorten_with_blank_value
+ client = Abrio::Client.new
+ assert_equal nil, client.shorten(nil)
+ assert_equal nil, client.shorten("")
+ end
+
+ def test_shorten_with_valid_value
+ client = Abrio::Client.new(:login => "rogleite", :key => "Z_VALID")
+
+ Abrio::Request.expects(:get).with("#{client.uri}/shorten", DEFAULT_EXPECTED_PARAMS).returns(abrio_success_xml)
+
+ abrio_url = client.shorten("http://google.com")
+ assert_not_nil abrio_url, "expects a Abrio::Url"
+ assert_equal "http://abr.io/18VN", abrio_url.short_url
+ end
+
+ def test_shorten_options_parameter
+ client = Abrio::Client.new(:login => "rogleite", :key => "Z_VALID")
+
+ expected_params = DEFAULT_EXPECTED_PARAMS.merge({:key => 'Z_OPTION', :login => 'login'})
+ Abrio::Request.expects(:get).with("http://abr.io/api/links/shorten", expected_params).returns(abrio_success_xml)
+
+ abrio_url = client.shorten("http://google.com", :uri => "http://abr.io/api/links", :login => "login", :key => "Z_OPTION")
+ assert_not_nil abrio_url, "expects a Abrio::Url"
+ assert_equal "OK", abrio_url.status_code
+ end
+
+ def test_shorten_failure
+ client = Abrio::Client.new(:login => "rogleite", :key => "Z_INVALID")
+
+ expected_params = DEFAULT_EXPECTED_PARAMS.merge({:key => 'Z_INVALID'})
+ Abrio::Request.expects(:get).with("#{client.uri}/shorten", expected_params).returns(abrio_error_xml)
+
+ abrio_url = client.shorten("http://google.com")
+ assert_not_nil abrio_url, "expects a Abrio::Url"
+ assert_equal "ERROR", abrio_url.status_code
+ assert_nil abrio_url.short_url
+ end
+
+ def test_shorten_net_http_error
+ expected_params = DEFAULT_EXPECTED_PARAMS.merge({:key => 'Z_INVALID'})
+ Abrio::Request.expects(:get).with("http://nonexist/shorten", expected_params).raises(Abrio::Error, "Net fake error")
+
+ client = Abrio::Client.new(:login => "rogleite", :key => "Z_INVALID")
+ abrio_url = client.shorten("http://google.com", :uri => "http://nonexist")
+
+ assert_not_nil abrio_url, "expects a Abrio::Url"
+ assert_equal "ERROR", abrio_url.status_code
+ assert_nil abrio_url.short_url
+ end
+
+end
Oops, something went wrong.

0 comments on commit f59e04e

Please sign in to comment.