41
loading...
This website collects cookies to deliver better user experience
GET
and POST
requests and returns a JSON response. The front end Document-Object Model is manipulated by JS scripts that run with a successful fetch response, so the frontend user experiences a seamless single page application.User
must log in. They then are presented with a choice of options: Play Reversi, Leaderboard, and My Scores.My Scores
makes a fetch
call which routes to the ScoresController
's index
action and returns an array of JSON objects which are then mapped into Score
objects in JS and rendered on the page.class ScoresController < ApplicationController
def index
scores = Score.where(user_id: params[:user_id])
seralized_scores = scores.map do |score|
{points: score.points, created_at: score.created_at.strftime('%b %d, %Y at %l:%M%P')}
end
render json: seralized_scores
end
end
User
Objects.User
must log in and to access the same Board
. Once the front end receives a response from BoardController
, a board is rendered on the front end. Each user then takes turns placing tokens by making POST calls to the BoardController
's play
action.class BoardController < ApplicationController
def play
board_id = params[:board]["boardId"]
cell = params[:id]
board = Board.find(board_id)
if board.set(current_user(board), cell)
render json: board.cells_to_be_flipped
else
render json: {error: "You can't play here"}
end
end
end
User
to try again. If the move is successful, a JSON object is returned with each cell that needs to be updated.components
and services
. While components
holds each object and object methods, services
holds objects that are explicitly responsible for fetch requests.class UserAPI {
static getTopUsers() {
fetch(root + "/users")
.then(resp => resp.json())
.then(json => {
User.addAllTopUserDivs(json)
})
}
}
.includes
method to specify relationships to be included in the result set. If I can tell Active Record about the associations I plan to use later, ActiveRecord can load the data eagerly which reduces queries in iterative methods.class User < ApplicationRecord
def self.top_users
top_users = self.includes(:scores).sort_by { |user| -user.average_score}
top_users.map {|user| {user: user, average_score: user.average_score, games_played: user.scores.length}}
end
end