gem install rails-api
rails api new jokes --database=postgresql -T
git init
git add -A && git commit -m 'Initial commit'
class Joke < ActiveRecord::Base
validates :title, presence: true
validates :selftext, presence: true
validates :author, presence: true
validates :score, presence: true
validates :num_comments, presence: true
end
rails g migration create_jokes
class CreateJokes < ActiveRecord::Migration
def change
create_table :jokes do |t|
t.string :title, null: false
t.text :selftext, null: false
t.string :author, null: false
t.integer :score, null: false
t.integer :num_comments, null: false
t.timestamps
end
end
end
reddit = Snooby::Client.new
jokes = reddit.subreddit('dadjokes').posts
jokes.each do |joke|
j = Joke.new
j.username = joke.author
j.title = joke.title
j.body = joke.selftext
j.score = joke.score
j.num_comments = joke.num_comments
j.save!
puts "Created Dad Joke with title #{j.title} by #{j.author}"
end
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :jokes, only: [:index]
end
end
end
class Api::V1::JokesController < ApplicationController
def index
@jokes = Joke.All
render json: @jokes
end
end
Talk through it
Remember this? Show serialized API we want
Adapter Pattern
gem 'active_model_serializers', '0.8.3'
# app/serializers/joke_serializer.rb
class DadjokeSerializer < ActiveModel::Serializer
attributes :id, :title, :selftext, :author, :score, :num_comments
end
- Why would we put something like is_funny in our
Serializer
rather than ourModel
?
We update our config/routes.rb
file:
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :jokes, only: [:index]
get "/random", to: "jokes#show"
end
end
end
Show how AR Serializers take care of this for us
Say you wanted to make that Lorem Ipsum generator of dadjokes