SpringnoteClient Preview(RESTClient 활용)
April 13th, 2008
나는 스프링노트 REST API를 호출할 일이 있으면 자연스럽게 SpringnoteResources - 스프링노트 루비 라이브러리를 꺼내든다. 그런데 최근 그럴 수 없는 상황이 발생했다. SpringnoteResource는 레일스 2.0이상에 포함된 액티브리소스에 종속적인데, 적용하려던 프로젝트는 레일스 1.2를 사용하고 있었기 때문이다. RSpringnote를 사용해도 좋았겠지만 최근에 본 REST Client가 떠올라서 가볍게 구현해봤다(heroku 개발자가 만들었다).
결과물
레일스의 Association 비슷하게 사용할 수 있게 만들어봤다.
- note = Springnote('examplenote',
:app_key => 'application_key_here',
:user_openid => 'http://user.myid.net/',
:user_key => 'user_key_here')
puts note.pages.find(1).source
SpringnoteClient
그리고 간단한 래퍼 클래스들이다.
- %w(rubygems rest_client active_support cgi).each{|lib| require lib}
def Springnote(*params)
Springnote::Note.new(*params)
end
module Springnote
class Note
attr_accessor :name, :config
# config should have app_key, user_openid, user_key
def initialize(name, config)
@name, @config = name, config
end
def pages
CallProxy.new(Page, self)
end
def username
CGI.escape(@config[:user_openid] || 'anonymous')
end
def password
@config[:user_key] ? "#{@config[:user_key]}.#{@config[:app_key]}" : @config[:app_key]
end
def url(path = '/', params = '')
"http://api.springnote.com#{path}?domain=#{@name}&#{params}"
end
end
class CallProxy
def initialize(callee, *params)
@callee, @params = callee, params
end
def method_missing(method, *params, &block)
@callee.send(method, *(params + @params), &block)
end
end
class Page < RestClient::Resource
attr_accessor :note
def self.find(page_id, note)
self.new(note.url("/pages/#{page_id}"), note.username, note.password).fetch(note)
end
def fetch(note)
self.note = note
@hash = Hash.from_xml(get)['page']
self
end
def method_missing(method)
@hash[method.to_s]
end
end
end
좀 더 가다듬어 gem으로 배포할 예정이다. 오늘은 여기까지만.




Leave a Reply