2007/06/30

Book class for amazon

amazon 用のbook クラス考。テキストの中に isbn を探す始まるマークがみつかったら、Book クラスを呼び出す。
ItemLookup でamazon からのレスポンス XML は、Search で得られる結果とは異なり <Items><Item> 要素は1つ。指定したISBN がなければエラーXMLが返ってくる。

  item = Book.new(amazonxml).setup.item


amazon からのレスポンス xml を Book クラスに対して Book.new(xml) し...setup.item すると、Book の Struct で指定された要素を拾う。拾いたい要素のフルパスをコード内に記述しない方法の模索。

仮に<small><url>... <big><url>... といったように異なる親要素を持つ同一名の要素が レスポンス xml内 にあった場合で、
<big>要素の<url>要素 を拾いたい時、Book の Structに big_url とアンダーバーで要素名を連結するとその要素パスにマッチしたデータを探す。

Book クラス @h の中身は、{ [アマゾンXML の要素フルパス]=> 要素のテキスト ...]

#require 'time'
#require 'uri'
#require 'net/http'
#require "rexml/document"

class Book < Struct.new(:mediumimage_url, :detailpageurl, :author, :isbn, :publisher, :publicationdate, :title, :listprice_amount)

  def initialize(xml=nil)
    @getxml = REXML::Document.new(xml)
    #@tplxml = Tpl.new().tplamazon
    str = '<?xml version="1.0" encoding="utf-8"?>
    <?xml-stylesheet type="text/xsl" href="amazon.xsl"?>
    <docroot>
      <link rel="alternate" type="text/html" href="http://www.midore.net/"/>
      <modified/>
      <Items/>
    </docroot>'
    @tplxml = REXML::Document.new(str)
    @h = Hash.new
  end
  
  def errorcheck
    @tplxml = nil
  end

  def setup
    get_ele() if @h.empty?
    @h.each{|k,v|
      members.select{|x| self[x] = v if k.downcase.include?(x)}
    }
    #unless detailpageurl.nil?
      #durl = detailpageurl.scan(/\/.\/ASIN\/.*?%/).last.gsub("%",'') 
      #self.detailpageurl = 'http://www.amazon.co.jp' + durl
    #end
    return self
  end
  
  def item
    return nil if @tplxml.nil?
    item = REXML::Element.new('item')
    each_pair{|k,v| 
      item.add_element(k.to_s).add_text(v.to_s)
    }
    return item
  end

  def get_ele(ele=nil)
    ele = @getxml.root if ele.nil?
    errorcheck if ele.to_s.include?('Error')
    return nil if @tplxml.nil?
    ele.each{|x| 
        get_ele(x.entries) if x.has_elements?
      @h[x.xpath.to_s.gsub("/", '_')] ||= x.text unless x.text.nil?
      }
  end

end 

p Book.new(amazonxml)
#<struct May::AmazonAWS::Book mediumimage_url=nil, detailpageurl=nil, author=nil, isbn=nil, publisher=nil, publicationdate=nil, title=nil, listprice_amount=nil>

p item = Book.new(amazonxml).setup.item
item 要素に自分が欲しい要素だけを集めてある。
<item> ... </>

最終的な item 要素の中身

<item>
<mediumimage_url/>
<detailpageurl/>
<author/>
<isbn/>
<publisher/>
<publicationdate/>
<title/>
<listprice_amount/>
</item>


問題点 :
1, 著者が複数だった場合はどうする?
2, 画像サイズ指定し忘れた。
3, 表示させる要素に ISBN or EAN を含めるべきかどうか。その他、etc

--imported_from
http://www.midore.net/daybook/2007/06/1183167964.html

0 件のコメント: