Last active
August 29, 2015 14:09
-
-
Save revskill/d9bd4b5a4ce0e3eedebb to your computer and use it in GitHub Desktop.
Wordpress API in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'JdbcActiveRecordExample' | |
run Sinatra::Application |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
gem 'jdbc-mysql' | |
gem 'activerecord-jdbcmysql-adapter' | |
gem 'puma' | |
gem 'sinatra' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "jdbc/mysql" | |
require "java" | |
require 'sinatra' | |
require 'active_record' | |
require 'json' | |
# Change the following to reflect your database settings | |
ActiveRecord::Base.establish_connection( | |
adapter: 'jdbcmysql', | |
username: 'root', | |
password: '123456', | |
database: 'test2' | |
) | |
class Post < ActiveRecord::Base | |
self.table_name = 'wp_posts' | |
self.primary_key = 'ID' | |
belongs_to :author, class_name: 'User', foreign_key: 'post_author' | |
end | |
class User < ActiveRecord::Base | |
self.table_name = 'wp_users' | |
self.primary_key = 'ID' | |
has_many :posts, class_name: 'Post', foreign_key: 'post_author' | |
end | |
get '/authors' do | |
content_type 'json' | |
User.all.to_json | |
end | |
get '/authors/:id' do | |
content_type 'json' | |
User.find(params[:id]).to_json | |
end | |
get '/authors/:author_id/posts' do | |
content_type 'json' | |
user = User.find(params[:author_id]) | |
if user | |
user.posts.to_json | |
else | |
[].to_json | |
end | |
end |
looks good, few feedbacks:
line 35: find
would raise exception if the record is not found, I think it'd better to use find_by_id
and have a condition to check if record is found or not and respond with a HTTP code like 404
The DB schema is the Wordpress database. The example is not production ready of course ;), it's just a proof of concept.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How's the DB schema like?