Sha256: 6990c16d7630f762649091184038734e96c2290680922e81703eb6873cf7a0bb

Contents?: true

Size: 1.35 KB

Versions: 1

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 => 'ndl-dl', :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

1 entries across 1 versions & 1 rubygems

Version Path
kindai-2.3.0 lib/kindai/searcher.rb