Sha256: d5c2450754e422664106b41e548250f0496efec789041aa09c1e399af5266267

Contents?: true

Size: 1.68 KB

Versions: 2

Compression:

Stored size: 1.68 KB

Contents

require 'uri'
require 'rexml/document'
require 'faraday'
require 'firebrew/firefox/basic_extension'

module Firebrew::AmoApi
  class Search < Firebrew::Firefox::BasicExtension
    def self.connection=(val)
      @connection = val
    end
    
    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,
        type: 'all',
        max: 30,
        os: 'all',
        version: '',
      }
      URI.encode(path_source % default_params.merge(params))
    end
    
    def self.fetch(params={})
      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, %[Extension not found: like "#{params[:term]}"] if results.empty?
      results
    end
    
    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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
firebrew-0.3.0 lib/firebrew/amo_api/search.rb
firebrew-0.2.0 lib/firebrew/amo_api/search.rb