Skip to content

Instantly share code, notes, and snippets.

@DylanFM
Created April 9, 2010 06:22
Show Gist options
  • Select an option

  • Save DylanFM/360936 to your computer and use it in GitHub Desktop.

Select an option

Save DylanFM/360936 to your computer and use it in GitHub Desktop.
class Post
attr_accessor :data
def initialize(data)
@data = Hashie::Mash.new(data)
end
def method_missing(key, *args)
data.send(key)
end
def self.all(options = {})
Tumblr::Post.all(options).map { |post| Post.new(post) }
end
def self.first(options = {})
Post.new(Tumblr::Post.first(options))
end
def self.find(id)
Post.new(Tumblr::Post.find(id))
end
class << self
alias_method :get, :find
end
end
module Tumblr
class InvalidAction < StandardError; end
class InvalidAPIResponse < StandardError; end
class Post
DEFAULTS = {}
# Options:
# start - The post offset to start from. The default is 0.
# num - The number of posts to return. The default is 20, and the maximum is 50.
# type - The type of posts to return. If unspecified or empty, all types of posts are returned. Must be one of text, quote, photo, link, chat, video, or audio.
# id - A specific post ID to return. Use instead of start, num, or type.
# filter - Alternate filter to run on the text content. Allowed values:
# text - Plain text only. No HTML.
# none - No post-processing. Output exactly what the author entered. (Note: Some authors write in Markdown, which will not be converted to HTML when this option is used.)
# tagged - Return posts with this tag in reverse-chronological order (newest first). Optionally specify chrono=1 to sort in chronological order (oldest first).
# search - Search for posts with this query.
def self.all(options = {})
Tumblr::Request.read(DEFAULTS.merge(options))["tumblr"]["posts"]["post"]
end
def self.first(options)
self.all(options.merge({ :num => 1 }))
end
def self.find(id)
self.all(:id => id)
end
class << self
alias_method :get, :find
end
end
class Request
KNOWN_ACTIONS = ["read"]
def self.method_missing(action, *args)
begin
# Try to execute it to tumblr
options = args[0]
self.do(action.to_s, options)
rescue Tumblr::InvalidAction => e
raise NoMethodError
end
end
private
def self.do(action, options = {})
# Make sure we understand this action
raise Tumblr::InvalidAction unless KNOWN_ACTIONS.include?(action)
# Make the request
response = HTTParty.get("http://#{TUMBLR}.tumblr.com/api/#{action}", :query => options)
# The response should be a hash
raise Tumblr::InvalidAPIResponse unless response.is_a? Hash
# Return the response
response
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment