Skip to content

Instantly share code, notes, and snippets.

@citrus
Created June 17, 2014 04:51
Show Gist options
  • Save citrus/a9cb04002ac2db2edf0a to your computer and use it in GitHub Desktop.
Save citrus/a9cb04002ac2db2edf0a to your computer and use it in GitHub Desktop.
Ruby wordpress API connector - For use with WP-API
require 'uri'
require 'net/http'
class Blog
class Connection
def request(url, &block)
req = Net::HTTP::Get.new(url)
req.basic_auth(ENV['blog_user'], ENV['blog_password']) if ENV['blog_user']
http.request(req, &block)
end
def get_json(url)
response = request(url)
case response
when Net::HTTPSuccess
JSON.parse(response.body)
else
raise "Request Error"
end
end
def uri
@url ||= URI.parse("http://#{ENV['blog_domain']}")
end
def http
@http ||= Net::HTTP.start(uri.host, uri.port)
end
end
def self.posts(options=nil)
options = options.to_query unless options.nil?
connection.get_json([ "/wp-json/posts", options ].compact.join("?")).map{ |i| Post.new(i) }
end
def self.post(id)
Post.new(connection.get_json("/wp-json/posts/#{id}"))
end
def self.connection
@connection ||= Connection.new
end
end
class Post
attr_reader :json
def initialize(json)
@json = json
end
def id
json['ID']
end
def title
json['title']
end
def slug
json['slug']
end
def content
json['content']
end
def posted_at
Date.parse(json['modified'])
end
def featured_image
img = json['featured_image']
img.blank? ? nil : img['source']
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment