All Files ( 100.0% covered at 1.7 hits/line )
19 files in total.
170 relevant lines,
170 lines covered and
0 lines missed.
(
100.0%
)
- 1
module Api
- 1
module V1
- 1
class BaseController < ApplicationController
- 1
rescue_from ActiveRecord::RecordNotFound, with: :not_found
- 1
rescue_from ActiveRecord::RecordInvalid, with: :unprocessable_entity
- 1
private
- 1
def not_found
- 2
render json: { error: 'Record not found' }, status: :not_found
end
- 1
def unprocessable_entity(exception)
- 6
render json: { errors: exception.record.errors.full_messages }, status: :unprocessable_entity
end
end
end
end
- 1
module Api
- 1
module V1
- 1
class JobsController < BaseController
- 1
include Paginatable
- 1
include Cacheable
- 1
before_action :set_job, only: [:show, :update, :destroy]
# GET /api/v1/jobs
#
# Mengambil daftar job dengan opsi filter dan pagination.
#
# @option params [Integer] :user_id (optional) Filter berdasarkan user ID
# @option params [Integer] :page (optional) Nomor halaman, default: 1
# @option params [Integer] :per_page (optional) Jumlah item per halaman, default: 10
#
# @return [JSON] Daftar job yang sudah dipaginasi dan difilter
- 1
def index
- 2
jobs_scope = filter_jobs.order(created_at: :desc)
- 2
paginated_jobs = jobs_scope.page(current_page).per(per_page)
- 2
cache_key = ActiveSupport::Cache.expand_cache_key([
'jobs/index',
"user-#{filter_params || 'all'}",
"updated-#{jobs_scope.maximum(:updated_at)&.to_i || 0}",
"page-#{current_page}",
"per_page-#{per_page}"])
- 2
serialized_jobs = Rails.cache.fetch(cache_key, expires_in: 1.hour) do
- 2
ActiveModelSerializers::SerializableResource.new(
paginated_jobs,
each_serializer: JobSerializer
).as_json
end
- 2
render_success(
serialized_jobs,
meta: pagination_meta(paginated_jobs)
)
end
# GET /api/v1/jobs/:id
# Menampilkan detail dari sebuah job berdasarkan ID
# @return [JSON] Job detail
- 1
def show
- 1
cache_key = "jobs/show/#{@job.id}/updated-#{@job.updated_at.to_i}"
- 1
job_data = Rails.cache.fetch(cache_key, expires_in: 1.hour) do
- 1
JobSerializer.new(@job).as_json
end
- 1
render_success(job_data)
end
# POST /api/v1/jobs
# @param job [Hash] Job attributes
# @return [JSON] Created job
- 1
def create
- 4
new_job = Job.create!(job_params)
- 1
invalidate_cache("jobs", skip_show: true)
- 1
render_success(new_job, status: :created, serializer: JobSerializer)
end
# PATCH/PUT /api/v1/jobs/:id
# @param job [Hash] Updated job attributes
# @return [JSON] Updated job
- 1
def update
- 2
@job.update!(job_params)
- 1
invalidate_cache("jobs", id: @job.id) # invalidate index + show cache per ID
- 1
render_success(@job, serializer: JobSerializer)
end
# DELETE /api/v1/jobs/:id
# @return [204 No Content]
- 1
def destroy
- 1
@job.destroy!
- 1
invalidate_cache("jobs", id: @job.id) # invalidate index + show cache per ID
- 1
head :no_content
end
- 1
private
# hooks rails
# Mencari job berdasarkan ID dari params[:id]
# @return [Job]
- 1
def set_job
- 5
@job = Job.find(params[:id])
end
# Rails strong parameters. Tujuannya untuk whitelist data yang boleh diterima dari request params[:job].
- 1
def job_params
- 6
params.require(:job).permit(:title, :description, :status, :user_id)
end
# Filter jobs jika user_id tersedia
# @return [ActiveRecord::Relation]
- 1
def filter_jobs
- 2
filter_params ? Job.where(user_id: filter_params) : Job.all
end
# Mengembalikan user_id dari params jika ada
# @return [String, nil]
- 1
def filter_params
- 5
params[:user_id].to_i if params[:user_id].present?
end
# Menampilkan response JSON sukses
# @param data [Object, nil] Data untuk ditampilkan (bisa nil)
# @param status [Symbol] HTTP status code
# @param options [Hash] Tambahan opsi render (misal serializer)
- 1
def render_success(data, status: :ok, meta: nil, serializer: nil, each_serializer: nil)
- 5
serialized = ActiveModelSerializers::SerializableResource.new(
data,
serializer: serializer,
each_serializer: each_serializer
).as_json
- 5
response = { data: serialized }
- 5
response[:meta] = meta if meta.present?
- 5
render json: response, status: status
end
end
end
end
- 1
module Api
- 1
module V1
- 1
class UsersController < BaseController
- 1
include Paginatable
- 1
include Cacheable
- 1
before_action :set_user, only: [:show, :update, :destroy]
# GET /api/v1/users
# Menampilkan daftar user dengan pagination dan cache
- 1
def index
- 1
users_scope = User.order(created_at: :desc)
- 1
paginated_users = users_scope.page(current_page).per(per_page)
cache_key = [
- 1
'users/index',
"updated-#{users_scope.maximum(:updated_at)&.to_i || 0}",
"page-#{current_page}",
"per_page-#{per_page}"
].join('/')
- 1
serialized_users = Rails.cache.fetch(cache_key, expires_in: 1.hour) do
- 1
ActiveModelSerializers::SerializableResource.new(
paginated_users,
each_serializer: UserSerializer
).as_json
end
- 1
render_success(
serialized_users,
meta: pagination_meta(paginated_users)
)
end
# GET /api/v1/users/:id
- 1
def show
- 1
cache_key = "users/show/#{@user.id}/updated-#{@user.updated_at.to_i}"
- 1
user_data = Rails.cache.fetch(cache_key, expires_in: 1.hour) do
- 1
UserSerializer.new(@user).as_json
end
- 1
render_success(user_data)
end
# POST /api/v1/users
- 1
def create
- 2
user = User.create!(user_params)
- 1
invalidate_cache("users", skip_show: true)
- 1
render_success(user, status: :created, serializer: UserSerializer)
end
# PATCH/PUT /api/v1/users/:id
- 1
def update
- 2
@user.update!(user_params)
- 1
invalidate_cache("users", id: @user.id)
- 1
render_success(@user, serializer: UserSerializer)
end
# DELETE /api/v1/users/:id
- 1
def destroy
- 2
@user.destroy
- 2
invalidate_cache("users", id: @user.id)
- 2
head :no_content
end
- 1
private
# hooks rails
# Mencari user berdasarkan ID dari params[:id]
# @return [User]
- 1
def set_user
- 6
@user = User.find(params[:id])
end
# Rails strong parameters. Tujuannya untuk whitelist data yang boleh diterima dari request params[:user].
- 1
def user_params
- 4
params.require(:user).permit(:name, :email, :phone)
end
# Menampilkan response JSON sukses
# @param data [Object, nil] Data untuk ditampilkan (bisa nil)
# @param status [Symbol] HTTP status code
# @param options [Hash] Tambahan opsi render (misal serializer)
- 1
def render_success(data, status: :ok, meta: nil, serializer: nil, each_serializer: nil)
- 4
serialized = ActiveModelSerializers::SerializableResource.new(
data,
serializer: serializer,
each_serializer: each_serializer
).as_json
- 4
response = { data: serialized }
- 4
response[:meta] = meta if meta.present?
- 4
render json: response, status: status
end
end
end
end
- 1
class ApplicationController < ActionController::API
end
# app/controllers/concerns/cacheable.rb
- 1
module Cacheable
- 1
extend ActiveSupport::Concern
# Menghapus cache terkait job tertentu (dan index)
- 1
def invalidate_cache(namespace, id: nil, skip_show: false)
- 7
Rails.logger.info("[CACHE] Deleting #{namespace}/index/*")
- 7
Rails.cache.delete_matched("#{namespace}/index/*")
- 7
unless skip_show || id.nil?
- 5
Rails.logger.info("[CACHE] Deleting #{namespace}/show/#{id}/*")
- 5
Rails.cache.delete_matched("#{namespace}/show/#{id}/*")
end
end
end
# app/controllers/concerns/paginatable.rb
- 1
module Paginatable
- 1
extend ActiveSupport::Concern
- 1
DEFAULT_PER_PAGE = 10
- 1
MAX_PER_PAGE = 100
- 1
def current_page
- 6
params[:page].presence || 1
end
- 1
def per_page
- 6
raw = params[:per_page].to_i
- 6
raw = DEFAULT_PER_PAGE if raw <= 0
- 6
[raw, MAX_PER_PAGE].min
end
- 1
def pagination_meta(collection)
{
- 3
current_page: collection.current_page,
total_pages: collection.total_pages,
total_count: collection.total_count,
per_page: collection.limit_value
}
end
end
- 1
class ApplicationRecord < ActiveRecord::Base
- 1
primary_abstract_class
end
- 1
class Job < ApplicationRecord
- 1
belongs_to :user
- 1
validates :title, presence: true
- 1
validates :description, presence: true
- 1
validates :status, presence: true, inclusion: { in: ['pending', 'in_progress', 'completed'] }
end
- 1
class User < ApplicationRecord
- 1
has_many :jobs, dependent: :destroy
- 1
validates :name, presence: true
- 1
validates :email, presence: true, uniqueness: true, format: { with: URI::MailTo::EMAIL_REGEXP }
- 1
validates :phone, presence: true
end
- 1
class JobSerializer < ActiveModel::Serializer
- 1
attributes :id, :title, :description, :status, :user_id, :created_at, :updated_at
- 1
belongs_to :user
end
- 1
class UserSerializer < ActiveModel::Serializer
- 1
attributes :id, :name, :email, :phone, :created_at, :updated_at
- 1
has_many :jobs
end
- 1
require_relative "boot"
- 1
require "rails/all"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
- 1
Bundler.require(*Rails.groups)
- 1
module InterviewTestApi
- 1
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
- 1
config.load_defaults 8.0
# Please, add to the `ignore` list any other `lib` subdirectories that do
# not contain `.rb` files, or that should not be reloaded or eager loaded.
# Common ones are `templates`, `generators`, or `middleware`, for example.
- 1
config.autoload_lib(ignore: %w[assets tasks])
# Configuration for the application, engines, and railties goes here.
#
# These settings can be overridden in specific environments using the files
# in config/environments, which are processed later.
#
# config.time_zone = "Central Time (US & Canada)"
# config.eager_load_paths << Rails.root.join("extras")
# Only loads a smaller set of middleware suitable for API only apps.
# Middleware like session, flash, cookies can be added back manually.
# Skip views, helpers and assets when generating a new resource.
- 1
config.api_only = true
end
end
- 1
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__)
- 1
require "bundler/setup" # Set up gems listed in the Gemfile.
- 1
require "bootsnap/setup" # Speed up boot time by caching expensive operations.
# Load the Rails application.
- 1
require_relative "application"
# Initialize the Rails application.
- 1
Rails.application.initialize!
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
- 1
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# While tests run files are not watched, reloading is not necessary.
- 1
config.enable_reloading = false
# Eager loading loads your entire application. When running a single test locally,
# this is usually not necessary, and can slow down your test suite. However, it's
# recommended that you enable it in continuous integration systems to ensure eager
# loading is working properly before deploying your code.
- 1
config.eager_load = ENV["CI"].present?
# Configure public file server for tests with cache-control for performance.
- 1
config.public_file_server.headers = { "cache-control" => "public, max-age=3600" }
# Show full error reports.
- 1
config.consider_all_requests_local = true
- 1
config.cache_store = :null_store
# Render exception templates for rescuable exceptions and raise for other exceptions.
- 1
config.action_dispatch.show_exceptions = :rescuable
# Disable request forgery protection in test environment.
- 1
config.action_controller.allow_forgery_protection = false
# Store uploaded files on the local file system in a temporary directory.
- 1
config.active_storage.service = :test
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
- 1
config.action_mailer.delivery_method = :test
# Set host to be used by links generated in mailer templates.
- 1
config.action_mailer.default_url_options = { host: "example.com" }
# Print deprecation notices to the stderr.
- 1
config.active_support.deprecation = :stderr
# Raises error for missing translations.
# config.i18n.raise_on_missing_translations = true
# Annotate rendered view with file names.
# config.action_view.annotate_rendered_view_with_filenames = true
# Raise error when a before_action's only/except options reference missing actions.
- 1
config.action_controller.raise_on_missing_callback_actions = true
end
# Be sure to restart your server when you modify this file.
# Avoid CORS issues when API is called from the frontend app.
# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin Ajax requests.
# Read more: https://github.com/cyu/rack-cors
- 1
Rails.application.config.middleware.insert_before 0, Rack::Cors do
- 1
allow do
- 1
origins "*"
- 1
resource "*",
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
# Be sure to restart your server when you modify this file.
# Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file.
# Use this to limit dissemination of sensitive information.
# See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors.
- 1
Rails.application.config.filter_parameters += [
:passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, :cvv, :cvc
]
# Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format. Inflections
# are locale specific, and you may define rules for as many different
# locales as you wish. All of these examples are active by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.plural /^(ox)$/i, "\\1en"
# inflect.singular /^(ox)en/i, "\\1"
# inflect.irregular "person", "people"
# inflect.uncountable %w( fish sheep )
# end
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.acronym "RESTful"
# end
- 1
Rails.application.routes.draw do
# API routes
- 1
namespace :api do
- 1
namespace :v1 do
- 1
resources :users
- 1
resources :jobs
end
end
# Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500.
# Can be used by load balancers and uptime monitors to verify that the app is live.
- 1
get "up" => "rails/health#show", as: :rails_health_check
end