loading
Generated 2025-06-03T17:20:18+07:00

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% )
File % covered Lines Relevant Lines Lines covered Lines missed Avg. Hits / Line
app/controllers/api/v1/base_controller.rb 100.00 % 18 10 10 0 1.60
app/controllers/api/v1/jobs_controller.rb 100.00 % 126 44 44 0 1.91
app/controllers/api/v1/users_controller.rb 100.00 % 101 40 40 0 1.63
app/controllers/application_controller.rb 100.00 % 2 1 1 0 1.00
app/controllers/concerns/cacheable.rb 100.00 % 15 8 8 0 4.25
app/controllers/concerns/paginatable.rb 100.00 % 26 12 12 0 2.83
app/models/application_record.rb 100.00 % 3 2 2 0 1.00
app/models/job.rb 100.00 % 7 5 5 0 1.00
app/models/user.rb 100.00 % 7 5 5 0 1.00
app/serializers/job_serializer.rb 100.00 % 4 3 3 0 1.00
app/serializers/user_serializer.rb 100.00 % 4 3 3 0 1.00
config/application.rb 100.00 % 32 8 8 0 1.00
config/boot.rb 100.00 % 4 3 3 0 1.00
config/environment.rb 100.00 % 5 2 2 0 1.00
config/environments/test.rb 100.00 % 53 13 13 0 1.00
config/initializers/cors.rb 100.00 % 16 4 4 0 1.00
config/initializers/filter_parameter_logging.rb 100.00 % 8 1 1 0 1.00
config/initializers/inflections.rb 100.00 % 16 0 0 0 0.00
config/routes.rb 100.00 % 13 6 6 0 1.00

app/controllers/api/v1/base_controller.rb

100.0% lines covered

10 relevant lines. 10 lines covered and 0 lines missed.
    
  1. 1 module Api
  2. 1 module V1
  3. 1 class BaseController < ApplicationController
  4. 1 rescue_from ActiveRecord::RecordNotFound, with: :not_found
  5. 1 rescue_from ActiveRecord::RecordInvalid, with: :unprocessable_entity
  6. 1 private
  7. 1 def not_found
  8. 2 render json: { error: 'Record not found' }, status: :not_found
  9. end
  10. 1 def unprocessable_entity(exception)
  11. 6 render json: { errors: exception.record.errors.full_messages }, status: :unprocessable_entity
  12. end
  13. end
  14. end
  15. end

app/controllers/api/v1/jobs_controller.rb

100.0% lines covered

44 relevant lines. 44 lines covered and 0 lines missed.
    
  1. 1 module Api
  2. 1 module V1
  3. 1 class JobsController < BaseController
  4. 1 include Paginatable
  5. 1 include Cacheable
  6. 1 before_action :set_job, only: [:show, :update, :destroy]
  7. # GET /api/v1/jobs
  8. #
  9. # Mengambil daftar job dengan opsi filter dan pagination.
  10. #
  11. # @option params [Integer] :user_id (optional) Filter berdasarkan user ID
  12. # @option params [Integer] :page (optional) Nomor halaman, default: 1
  13. # @option params [Integer] :per_page (optional) Jumlah item per halaman, default: 10
  14. #
  15. # @return [JSON] Daftar job yang sudah dipaginasi dan difilter
  16. 1 def index
  17. 2 jobs_scope = filter_jobs.order(created_at: :desc)
  18. 2 paginated_jobs = jobs_scope.page(current_page).per(per_page)
  19. 2 cache_key = ActiveSupport::Cache.expand_cache_key([
  20. 'jobs/index',
  21. "user-#{filter_params || 'all'}",
  22. "updated-#{jobs_scope.maximum(:updated_at)&.to_i || 0}",
  23. "page-#{current_page}",
  24. "per_page-#{per_page}"])
  25. 2 serialized_jobs = Rails.cache.fetch(cache_key, expires_in: 1.hour) do
  26. 2 ActiveModelSerializers::SerializableResource.new(
  27. paginated_jobs,
  28. each_serializer: JobSerializer
  29. ).as_json
  30. end
  31. 2 render_success(
  32. serialized_jobs,
  33. meta: pagination_meta(paginated_jobs)
  34. )
  35. end
  36. # GET /api/v1/jobs/:id
  37. # Menampilkan detail dari sebuah job berdasarkan ID
  38. # @return [JSON] Job detail
  39. 1 def show
  40. 1 cache_key = "jobs/show/#{@job.id}/updated-#{@job.updated_at.to_i}"
  41. 1 job_data = Rails.cache.fetch(cache_key, expires_in: 1.hour) do
  42. 1 JobSerializer.new(@job).as_json
  43. end
  44. 1 render_success(job_data)
  45. end
  46. # POST /api/v1/jobs
  47. # @param job [Hash] Job attributes
  48. # @return [JSON] Created job
  49. 1 def create
  50. 4 new_job = Job.create!(job_params)
  51. 1 invalidate_cache("jobs", skip_show: true)
  52. 1 render_success(new_job, status: :created, serializer: JobSerializer)
  53. end
  54. # PATCH/PUT /api/v1/jobs/:id
  55. # @param job [Hash] Updated job attributes
  56. # @return [JSON] Updated job
  57. 1 def update
  58. 2 @job.update!(job_params)
  59. 1 invalidate_cache("jobs", id: @job.id) # invalidate index + show cache per ID
  60. 1 render_success(@job, serializer: JobSerializer)
  61. end
  62. # DELETE /api/v1/jobs/:id
  63. # @return [204 No Content]
  64. 1 def destroy
  65. 1 @job.destroy!
  66. 1 invalidate_cache("jobs", id: @job.id) # invalidate index + show cache per ID
  67. 1 head :no_content
  68. end
  69. 1 private
  70. # hooks rails
  71. # Mencari job berdasarkan ID dari params[:id]
  72. # @return [Job]
  73. 1 def set_job
  74. 5 @job = Job.find(params[:id])
  75. end
  76. # Rails strong parameters. Tujuannya untuk whitelist data yang boleh diterima dari request params[:job].
  77. 1 def job_params
  78. 6 params.require(:job).permit(:title, :description, :status, :user_id)
  79. end
  80. # Filter jobs jika user_id tersedia
  81. # @return [ActiveRecord::Relation]
  82. 1 def filter_jobs
  83. 2 filter_params ? Job.where(user_id: filter_params) : Job.all
  84. end
  85. # Mengembalikan user_id dari params jika ada
  86. # @return [String, nil]
  87. 1 def filter_params
  88. 5 params[:user_id].to_i if params[:user_id].present?
  89. end
  90. # Menampilkan response JSON sukses
  91. # @param data [Object, nil] Data untuk ditampilkan (bisa nil)
  92. # @param status [Symbol] HTTP status code
  93. # @param options [Hash] Tambahan opsi render (misal serializer)
  94. 1 def render_success(data, status: :ok, meta: nil, serializer: nil, each_serializer: nil)
  95. 5 serialized = ActiveModelSerializers::SerializableResource.new(
  96. data,
  97. serializer: serializer,
  98. each_serializer: each_serializer
  99. ).as_json
  100. 5 response = { data: serialized }
  101. 5 response[:meta] = meta if meta.present?
  102. 5 render json: response, status: status
  103. end
  104. end
  105. end
  106. end

app/controllers/api/v1/users_controller.rb

100.0% lines covered

40 relevant lines. 40 lines covered and 0 lines missed.
    
  1. 1 module Api
  2. 1 module V1
  3. 1 class UsersController < BaseController
  4. 1 include Paginatable
  5. 1 include Cacheable
  6. 1 before_action :set_user, only: [:show, :update, :destroy]
  7. # GET /api/v1/users
  8. # Menampilkan daftar user dengan pagination dan cache
  9. 1 def index
  10. 1 users_scope = User.order(created_at: :desc)
  11. 1 paginated_users = users_scope.page(current_page).per(per_page)
  12. cache_key = [
  13. 1 'users/index',
  14. "updated-#{users_scope.maximum(:updated_at)&.to_i || 0}",
  15. "page-#{current_page}",
  16. "per_page-#{per_page}"
  17. ].join('/')
  18. 1 serialized_users = Rails.cache.fetch(cache_key, expires_in: 1.hour) do
  19. 1 ActiveModelSerializers::SerializableResource.new(
  20. paginated_users,
  21. each_serializer: UserSerializer
  22. ).as_json
  23. end
  24. 1 render_success(
  25. serialized_users,
  26. meta: pagination_meta(paginated_users)
  27. )
  28. end
  29. # GET /api/v1/users/:id
  30. 1 def show
  31. 1 cache_key = "users/show/#{@user.id}/updated-#{@user.updated_at.to_i}"
  32. 1 user_data = Rails.cache.fetch(cache_key, expires_in: 1.hour) do
  33. 1 UserSerializer.new(@user).as_json
  34. end
  35. 1 render_success(user_data)
  36. end
  37. # POST /api/v1/users
  38. 1 def create
  39. 2 user = User.create!(user_params)
  40. 1 invalidate_cache("users", skip_show: true)
  41. 1 render_success(user, status: :created, serializer: UserSerializer)
  42. end
  43. # PATCH/PUT /api/v1/users/:id
  44. 1 def update
  45. 2 @user.update!(user_params)
  46. 1 invalidate_cache("users", id: @user.id)
  47. 1 render_success(@user, serializer: UserSerializer)
  48. end
  49. # DELETE /api/v1/users/:id
  50. 1 def destroy
  51. 2 @user.destroy
  52. 2 invalidate_cache("users", id: @user.id)
  53. 2 head :no_content
  54. end
  55. 1 private
  56. # hooks rails
  57. # Mencari user berdasarkan ID dari params[:id]
  58. # @return [User]
  59. 1 def set_user
  60. 6 @user = User.find(params[:id])
  61. end
  62. # Rails strong parameters. Tujuannya untuk whitelist data yang boleh diterima dari request params[:user].
  63. 1 def user_params
  64. 4 params.require(:user).permit(:name, :email, :phone)
  65. end
  66. # Menampilkan response JSON sukses
  67. # @param data [Object, nil] Data untuk ditampilkan (bisa nil)
  68. # @param status [Symbol] HTTP status code
  69. # @param options [Hash] Tambahan opsi render (misal serializer)
  70. 1 def render_success(data, status: :ok, meta: nil, serializer: nil, each_serializer: nil)
  71. 4 serialized = ActiveModelSerializers::SerializableResource.new(
  72. data,
  73. serializer: serializer,
  74. each_serializer: each_serializer
  75. ).as_json
  76. 4 response = { data: serialized }
  77. 4 response[:meta] = meta if meta.present?
  78. 4 render json: response, status: status
  79. end
  80. end
  81. end
  82. end

app/controllers/application_controller.rb

100.0% lines covered

1 relevant lines. 1 lines covered and 0 lines missed.
    
  1. 1 class ApplicationController < ActionController::API
  2. end

app/controllers/concerns/cacheable.rb

100.0% lines covered

8 relevant lines. 8 lines covered and 0 lines missed.
    
  1. # app/controllers/concerns/cacheable.rb
  2. 1 module Cacheable
  3. 1 extend ActiveSupport::Concern
  4. # Menghapus cache terkait job tertentu (dan index)
  5. 1 def invalidate_cache(namespace, id: nil, skip_show: false)
  6. 7 Rails.logger.info("[CACHE] Deleting #{namespace}/index/*")
  7. 7 Rails.cache.delete_matched("#{namespace}/index/*")
  8. 7 unless skip_show || id.nil?
  9. 5 Rails.logger.info("[CACHE] Deleting #{namespace}/show/#{id}/*")
  10. 5 Rails.cache.delete_matched("#{namespace}/show/#{id}/*")
  11. end
  12. end
  13. end

app/controllers/concerns/paginatable.rb

100.0% lines covered

12 relevant lines. 12 lines covered and 0 lines missed.
    
  1. # app/controllers/concerns/paginatable.rb
  2. 1 module Paginatable
  3. 1 extend ActiveSupport::Concern
  4. 1 DEFAULT_PER_PAGE = 10
  5. 1 MAX_PER_PAGE = 100
  6. 1 def current_page
  7. 6 params[:page].presence || 1
  8. end
  9. 1 def per_page
  10. 6 raw = params[:per_page].to_i
  11. 6 raw = DEFAULT_PER_PAGE if raw <= 0
  12. 6 [raw, MAX_PER_PAGE].min
  13. end
  14. 1 def pagination_meta(collection)
  15. {
  16. 3 current_page: collection.current_page,
  17. total_pages: collection.total_pages,
  18. total_count: collection.total_count,
  19. per_page: collection.limit_value
  20. }
  21. end
  22. end

app/models/application_record.rb

100.0% lines covered

2 relevant lines. 2 lines covered and 0 lines missed.
    
  1. 1 class ApplicationRecord < ActiveRecord::Base
  2. 1 primary_abstract_class
  3. end

app/models/job.rb

100.0% lines covered

5 relevant lines. 5 lines covered and 0 lines missed.
    
  1. 1 class Job < ApplicationRecord
  2. 1 belongs_to :user
  3. 1 validates :title, presence: true
  4. 1 validates :description, presence: true
  5. 1 validates :status, presence: true, inclusion: { in: ['pending', 'in_progress', 'completed'] }
  6. end

app/models/user.rb

100.0% lines covered

5 relevant lines. 5 lines covered and 0 lines missed.
    
  1. 1 class User < ApplicationRecord
  2. 1 has_many :jobs, dependent: :destroy
  3. 1 validates :name, presence: true
  4. 1 validates :email, presence: true, uniqueness: true, format: { with: URI::MailTo::EMAIL_REGEXP }
  5. 1 validates :phone, presence: true
  6. end

app/serializers/job_serializer.rb

100.0% lines covered

3 relevant lines. 3 lines covered and 0 lines missed.
    
  1. 1 class JobSerializer < ActiveModel::Serializer
  2. 1 attributes :id, :title, :description, :status, :user_id, :created_at, :updated_at
  3. 1 belongs_to :user
  4. end

app/serializers/user_serializer.rb

100.0% lines covered

3 relevant lines. 3 lines covered and 0 lines missed.
    
  1. 1 class UserSerializer < ActiveModel::Serializer
  2. 1 attributes :id, :name, :email, :phone, :created_at, :updated_at
  3. 1 has_many :jobs
  4. end

config/application.rb

100.0% lines covered

8 relevant lines. 8 lines covered and 0 lines missed.
    
  1. 1 require_relative "boot"
  2. 1 require "rails/all"
  3. # Require the gems listed in Gemfile, including any gems
  4. # you've limited to :test, :development, or :production.
  5. 1 Bundler.require(*Rails.groups)
  6. 1 module InterviewTestApi
  7. 1 class Application < Rails::Application
  8. # Initialize configuration defaults for originally generated Rails version.
  9. 1 config.load_defaults 8.0
  10. # Please, add to the `ignore` list any other `lib` subdirectories that do
  11. # not contain `.rb` files, or that should not be reloaded or eager loaded.
  12. # Common ones are `templates`, `generators`, or `middleware`, for example.
  13. 1 config.autoload_lib(ignore: %w[assets tasks])
  14. # Configuration for the application, engines, and railties goes here.
  15. #
  16. # These settings can be overridden in specific environments using the files
  17. # in config/environments, which are processed later.
  18. #
  19. # config.time_zone = "Central Time (US & Canada)"
  20. # config.eager_load_paths << Rails.root.join("extras")
  21. # Only loads a smaller set of middleware suitable for API only apps.
  22. # Middleware like session, flash, cookies can be added back manually.
  23. # Skip views, helpers and assets when generating a new resource.
  24. 1 config.api_only = true
  25. end
  26. end

config/boot.rb

100.0% lines covered

3 relevant lines. 3 lines covered and 0 lines missed.
    
  1. 1 ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__)
  2. 1 require "bundler/setup" # Set up gems listed in the Gemfile.
  3. 1 require "bootsnap/setup" # Speed up boot time by caching expensive operations.

config/environment.rb

100.0% lines covered

2 relevant lines. 2 lines covered and 0 lines missed.
    
  1. # Load the Rails application.
  2. 1 require_relative "application"
  3. # Initialize the Rails application.
  4. 1 Rails.application.initialize!

config/environments/test.rb

100.0% lines covered

13 relevant lines. 13 lines covered and 0 lines missed.
    
  1. # The test environment is used exclusively to run your application's
  2. # test suite. You never need to work with it otherwise. Remember that
  3. # your test database is "scratch space" for the test suite and is wiped
  4. # and recreated between test runs. Don't rely on the data there!
  5. 1 Rails.application.configure do
  6. # Settings specified here will take precedence over those in config/application.rb.
  7. # While tests run files are not watched, reloading is not necessary.
  8. 1 config.enable_reloading = false
  9. # Eager loading loads your entire application. When running a single test locally,
  10. # this is usually not necessary, and can slow down your test suite. However, it's
  11. # recommended that you enable it in continuous integration systems to ensure eager
  12. # loading is working properly before deploying your code.
  13. 1 config.eager_load = ENV["CI"].present?
  14. # Configure public file server for tests with cache-control for performance.
  15. 1 config.public_file_server.headers = { "cache-control" => "public, max-age=3600" }
  16. # Show full error reports.
  17. 1 config.consider_all_requests_local = true
  18. 1 config.cache_store = :null_store
  19. # Render exception templates for rescuable exceptions and raise for other exceptions.
  20. 1 config.action_dispatch.show_exceptions = :rescuable
  21. # Disable request forgery protection in test environment.
  22. 1 config.action_controller.allow_forgery_protection = false
  23. # Store uploaded files on the local file system in a temporary directory.
  24. 1 config.active_storage.service = :test
  25. # Tell Action Mailer not to deliver emails to the real world.
  26. # The :test delivery method accumulates sent emails in the
  27. # ActionMailer::Base.deliveries array.
  28. 1 config.action_mailer.delivery_method = :test
  29. # Set host to be used by links generated in mailer templates.
  30. 1 config.action_mailer.default_url_options = { host: "example.com" }
  31. # Print deprecation notices to the stderr.
  32. 1 config.active_support.deprecation = :stderr
  33. # Raises error for missing translations.
  34. # config.i18n.raise_on_missing_translations = true
  35. # Annotate rendered view with file names.
  36. # config.action_view.annotate_rendered_view_with_filenames = true
  37. # Raise error when a before_action's only/except options reference missing actions.
  38. 1 config.action_controller.raise_on_missing_callback_actions = true
  39. end

config/initializers/cors.rb

100.0% lines covered

4 relevant lines. 4 lines covered and 0 lines missed.
    
  1. # Be sure to restart your server when you modify this file.
  2. # Avoid CORS issues when API is called from the frontend app.
  3. # Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin Ajax requests.
  4. # Read more: https://github.com/cyu/rack-cors
  5. 1 Rails.application.config.middleware.insert_before 0, Rack::Cors do
  6. 1 allow do
  7. 1 origins "*"
  8. 1 resource "*",
  9. headers: :any,
  10. methods: [:get, :post, :put, :patch, :delete, :options, :head]
  11. end
  12. end

config/initializers/filter_parameter_logging.rb

100.0% lines covered

1 relevant lines. 1 lines covered and 0 lines missed.
    
  1. # Be sure to restart your server when you modify this file.
  2. # Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file.
  3. # Use this to limit dissemination of sensitive information.
  4. # See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors.
  5. 1 Rails.application.config.filter_parameters += [
  6. :passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, :cvv, :cvc
  7. ]

config/initializers/inflections.rb

100.0% lines covered

0 relevant lines. 0 lines covered and 0 lines missed.
    
  1. # Be sure to restart your server when you modify this file.
  2. # Add new inflection rules using the following format. Inflections
  3. # are locale specific, and you may define rules for as many different
  4. # locales as you wish. All of these examples are active by default:
  5. # ActiveSupport::Inflector.inflections(:en) do |inflect|
  6. # inflect.plural /^(ox)$/i, "\\1en"
  7. # inflect.singular /^(ox)en/i, "\\1"
  8. # inflect.irregular "person", "people"
  9. # inflect.uncountable %w( fish sheep )
  10. # end
  11. # These inflection rules are supported but not enabled by default:
  12. # ActiveSupport::Inflector.inflections(:en) do |inflect|
  13. # inflect.acronym "RESTful"
  14. # end

config/routes.rb

100.0% lines covered

6 relevant lines. 6 lines covered and 0 lines missed.
    
  1. 1 Rails.application.routes.draw do
  2. # API routes
  3. 1 namespace :api do
  4. 1 namespace :v1 do
  5. 1 resources :users
  6. 1 resources :jobs
  7. end
  8. end
  9. # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500.
  10. # Can be used by load balancers and uptime monitors to verify that the app is live.
  11. 1 get "up" => "rails/health#show", as: :rails_health_check
  12. end