lib/firebrew/amo_api/search.rb in firebrew-0.1.3 vs lib/firebrew/amo_api/search.rb in firebrew-0.2.0

- old
+ new

@@ -1,22 +1,19 @@ -require 'active_resource' require 'uri' +require 'rexml/document' +require 'faraday' require 'firebrew/firefox/basic_extension' module Firebrew::AmoApi - class Search < ActiveResource::Base - class Format - include ActiveResource::Formats::XmlFormat - - def decode(xml) - results = super(xml)['addon'] || [] - results.instance_of?(Array) ? results : [results] - end + class Search < Firebrew::Firefox::BasicExtension + def self.connection=(val) + @connection = val end - self.site = 'https://services.addons.mozilla.org' - self.format = Format.new + def self.connection + @connection ||= Faraday.new(url: 'https://services.addons.mozilla.org') + end def self.path(params={}) path_source = '/ja/firefox/api/%{api_version}/search/%{term}/%{type}/%{max}/%{os}/%{version}' default_params = { api_version: 1.5, @@ -27,24 +24,41 @@ } URI.encode(path_source % default_params.merge(params)) end def self.fetch(params={}) - self.find(:all, from: self.path(params)).to_a + response = self.connection.get(self.path params) + raise Firebrew::NetworkError, "Invalid HTTP status: #{response.status}" unless response.status == 200 + dom = REXML::Document.new response.body + addons = REXML::XPath.match(dom, '/searchresults/addon') + addons.map{|v| Search.new v} + + rescue Faraday::Error => e + m = e.message + m[0] = m[0].upcase + raise Firebrew::NetworkError, m end def self.fetch!(params={}) results = self.fetch(params) - raise Firebrew::ExtensionNotFoundError if results.empty? + raise Firebrew::ExtensionNotFoundError, %[Extension not found: like "#{params[:term]}"] if results.empty? results end - def extension - Firebrew::Firefox::BasicExtension.new( - name: self.name, - guid: self.guid, - uri: self.install, - version: self.version + attr_reader :data + + def initialize(data) + @data = data + + val = lambda do |name| + REXML::XPath.match(self.data, "#{name}/text()").first.value.strip + end + + super( + name: val[:name], + guid: val[:guid], + uri: val[:install], + version: val[:version] ) end end end