Ruby on Rails

or how to easily write a simple API

Short about Lovis

Why Ruby on Rails?

works perfectly for:

main API with microservices

prototyping/hackathon way

 

The good parts

ORM

Model

Serializer

The code case

The code case

USER

id

name

age

description

CUPS

id

name

description

year

seasonal

special edition

in_production

COLLECTED CUPS

user_id

cup_id

ActiveRecord

ORM

ActiveRecord

ORM

Model

class Cup < ActiveRecord::Base

  def self.by_year year
    where(year: year)
  end

  def self.seasonal
    where(seasonal: true)
  end

  def title
    "#{name}, #{year}"
  end
end

Relations

class User
  has_many :collected_cups
  has_many :cups, though: :collected_cups
end

class Cup
  has_many :collected_cups
  has_many :users, though: :collected_cups
end

class CollectedCup

end

Serializers

class UserSerializer < ActiveModel::Serializer
  attributes :id, :name

end
class UserFullSerializer < ActiveModel::Serializer
  has_many :cups, each_serializer: CupSerializer

  attributes :id, :name, :age, :member_since, :description
    
  def member_since
    object.created_at
  end
end

Use serializers

class UsersController
# localhost:3000/users
  def index
    users = User.all

    render json: users
  end
  
# localhost:3000/users/:id
  def show
    user = User.find params[:id]
    render json: user, serializer: UserFullSerializer
  end
end

Code case

In place:

List all cups, view a single one

List all users, view a single one

create a new user

List all collectors for a cup

to implement:

add and remove from collection

https://github.com/Lovis/mymble

Ruby on Rails

By indiefarmor

Ruby on Rails

  • 386