Sha256: a24073e3ae6dcb88ffe5a5bb93e7e8ad5098c9118f71c2043e1c7db7484dd8e2

Contents?: true

Size: 1.35 KB

Versions: 6

Compression:

Stored size: 1.35 KB

Contents

# -*- coding: utf-8 -*-
module Kindai
  class Searcher
    include Enumerable
    attr_accessor :keyword
    def self.search keyword
      Kindai::Util.logger.debug "keyword: #{keyword}"
      me = self.new
      me.keyword = keyword
      me
    end

    def length
      @length ||= total_of(@keyword)
    end

    def each
      (0..(1/0.0)).each{ |page|
        Kindai::Util.logger.debug "page #{page}"
        uris = result_for(@keyword, page)
        return if uris.empty?
        uris.each{ |uri|
          yield Kindai::Book.new_from_search_result_uri(uri)
        }
      }
    end

    protected
    def total_of(keyword)
      page = Nokogiri(Kindai::Util.fetch_uri(uri_for(keyword)))
      total = page.at('.//opensearch:totalResults', {"opensearch"=>"http://a9.com/-/spec/opensearchrss/1.0/"} ).content.to_i

      Kindai::Util.logger.debug "total: #{total}"
      total
    end

    def result_for keyword, page = 0
      page = Nokogiri Kindai::Util.fetch_uri(uri_for(keyword, page))
      page.search('item').map{ |item|
        item.at('link').content
      }
    end

    def uri_for keyword, page = 0
      count = 100
      params = { :any => keyword, :dpid => 'kindai', :idx => page * count + 1, :cnt => count}
      root = URI.parse("http://iss.ndl.go.jp/api/opensearch")
      path = '?' + Kindai::Util.expand_params(params)
      root + path
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
kindai-2.2.1 lib/kindai/searcher.rb
kindai-2.2.0 lib/kindai/searcher.rb
kindai-2.1.2 lib/kindai/searcher.rb
kindai-2.1.1 lib/kindai/searcher.rb
kindai-2.1.0 lib/kindai/searcher.rb
kindai-2.0.0 lib/kindai/searcher.rb