アーカイブ
RubyでFlickr APIのphotos.getInfoを呼ぶ
Net::Flickrをインストールしたら、flickr.photos.getInfoメソッドが実装されてなかったので良い機会なので実装してみた。
flickr apiをrubyで使う – replore的日記がとても参考になった。
FlickrAPIは普通にRESTなので、REXMLで取得してparseする。
今回自分で実装したのはgeotagまわりのため。FlickrのAPIの仕様でtagは小数点やハイフンが消されるので、その元の値を取るのにgetInfoメソッドが必要になる。Tagオブジェクトのrawからアクセスできるようにした。
使い方はphoto_idをコンストラクタに渡す。
info = PhotoInfo.new(photo_id)
info.tags.each{ |tag|
puts tag.raw
}
flickr-photos-getInfo.rb
require ’open-uri’
require ’rexml/document’
require ’cgi’FLICKR_API_KEY = ’your-api-key’
def flickr_call(method_name, arg_map={}.freeze)
args = arg_map.collect {|k,v| CGI.escape(k) << '=' << CGI.escape(v)}.join('&')
url = ”http://www.flickr.com/services/rest/?api_key=%s&method=%s&%s” %
[FLICKR_API_KEY, method_name, args]
doc = REXML::Document.new(open(url).read)
endclass PhotoInfo
@xml_doc
def initialize(photo_id)
@xml_doc = flickr_call(’flickr.photos.getInfo’, ’photo_id’ => photo_id)
end
def tags
tag_list = Array.new
REXML::XPath.each(@xml_doc, ’//tag’){ |tag|
tag_list << Tag.new(
’id’ => REXML::XPath.first(tag,’attribute::id’),
’author’ => REXML::XPath.first(tag,’attribute::author’),
’raw’ => REXML::XPath.first(tag,’attribute::raw’),
’tag’ => tag.text
)
}
return tag_list
end
endclass Tag
def initialize(args)
@id = args['id']
@author = args['author']
@raw = args['raw']
@tag = args['tag']
end
def id
@id
end
def author
@author.to_s
end
def raw
@raw.to_s
end
def tag
@tag.to_s
end
def is_machine
if @tag =~ /.+:.+=.+/
return true
else
return false
end
end
def is_geo
if @tag =~ /geo:.+=.+/
return true
else
return false
end
end
end

最近のコメント