Skip to content

Instantly share code, notes, and snippets.

@yuyalush
Forked from kastner/r.rb
Created January 29, 2012 14:53
Show Gist options
  • Save yuyalush/1699148 to your computer and use it in GitHub Desktop.
Save yuyalush/1699148 to your computer and use it in GitHub Desktop.
# Simple SimpleNote client library
# Erik Kastner 2010-07-18
require 'rubygems'
require 'rest_client'
require 'base64'
require 'json'
class SimpleNote
def initialize(email, password)
@email = email
@token = get_token(email, password)
end
def base
"https://simple-note.appspot.com/api/"
end
def client
@client ||= RestClient::Resource.new(base)
end
def get_token(email, password)
data = Base64.encode64("password=#{password}&email=#{email}")
client['login'].post(data)
end
def [](key)
if key.kind_of?(Fixnum)
Note.fetch(self, notes[key]["key"])
elsif key.kind_of?(String)
Note.fetch(self, key)
elsif key.kind_of?(Regexp)
search(key.source)
end
end
def search(query)
results = JSON.parse(client['search' + def_params(:query => query)].get)
return nil if results["Response"]["totalRecords"] == 0
results["Response"]["Results"].map {|r| Note.fetch(self, r["key"])}
end
def notes(force = false)
@notes = nil if force
@notes ||= JSON.parse(client['index' + def_params].get.to_s)
end
def new_note(note = nil)
Note.new(self, note)
end
def get_note(key)
client['note' + def_params(:key => key)].get
end
def put_note(note, key=nil)
note = Base64.encode64(note)
client['note' + def_params((key ? {:key => key} : {}))].post(note)
end
def del_note(key)
client['delete' + def_params(:key => key)].get
end
def def_params(hash = {})
params({:auth => @token, :email => @email}.merge(hash))
end
def params(hash)
'?' + RestClient::Payload.generate(hash).to_s
end
class Note
attr_accessor :key
attr_accessor :note
def self.fetch(simplenote, key)
new(simplenote, simplenote.get_note(key), key)
end
def initialize(simplenote, note="", key=nil)
@sn = simplenote
@note = note
@key = key
end
def save
@key = @sn.put_note(@note, @key).to_s
end
def delete
@sn.del_note(@key)
end
def to_s
@note
end
end
end
if $0 == __FILE__
simplenote = SimpleNote.new(email, password)
my_note = simplenote[/my note/].first # Find a note
my_note.note = my_note.to_s + "\nAnother line!"
my_note.save
new_note = simplenote.new_note
new_note.note = "All around the mullberry bush"
new_note.save
first_note = simplenote[0]
puts first_note
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment