2009年9月20日日曜日

[Rails][WebAPI] ActiveResourceでYahoo!API (2) [かな漢字変換]

かな漢字変換サービスのサンプルクライアント追加。

↓テキスト解析API かな漢字変換 サンプル
http://yahooapi-petit-sample.heroku.com/jim_service/segments/analyze


モデル(ActiveResource)はこんな感じ。
# app/model/jim_service/segment.rb

class JimService::Segment < ActiveResource::Base

class Format
def extension() '' end
def mime_type() 'application/xml' end
def encode(hash, options = {}) hash.to_xml(options) end
def decode(xml)
data = Hash.from_xml(xml)['ResultSet']['Result']['SegmentList']['Segment']
data = [ data ] if data.is_a?(Hash)
data.each{ |seg|
if seg['CandidateList'] == nil
seg.store 'CandidateList', {'Candidate'=>[]} if seg['CandidateList'] == nil
elsif seg['CandidateList']['Candidate'].is_a?(String)
cand = seg['CandidateList']['Candidate']
seg['CandidateList']['Candidate'] = [ cand ]
end

}
data
end
end

self.site = 'http://jlp.yahooapis.jp'
self.format = Format.new

class << self
def collection_path(prefix_options = {}, query_options = nil)
prefix_options, query_options = split_options(prefix_options) if query_options.nil?
"/JIMService/V1/conversion#{query_string(query_options)}"
end
end

end


リクエストによってXMLが若干違ってくる(要素があったりなかったり)のと、入れ子のHashを扱うのとで、Format.decode()が少しごちゃごちゃしている。

0 件のコメント:

コメントを投稿