Class: JLPT::ActiveModel::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/jlpt/active_model/validator.rb

Overview

ActiveModel Validator enforcing JLPT level difficulty constraints on Rails models.

Examples:

Usage in Rails Model

class Lesson < ApplicationRecord
  validates :content, jlpt_level: { max_level: :n3 }
end

Constant Summary collapse

LEVEL_VALS =
{ n5: 1, n4: 2, n3: 3, n2: 4, n1: 5 }.freeze

Class Method Summary collapse

Class Method Details

.validate(record, attribute, value, max_level: :n3) ⇒ Object

Validate model attribute against max_level constraint

Parameters:

  • record (Object)

    Rails model instance

  • attribute (Symbol)

    attribute name

  • value (String)

    text content

  • max_level (Symbol) (defaults to: :n3)

    maximum allowed level (:n5, :n4, :n3, :n2)



22
23
24
25
26
27
# File 'lib/jlpt/active_model/validator.rb', line 22

def validate(record, attribute, value, max_level: :n3)
  return if value.nil? || value.to_s.strip.empty?

  res = JLPT.analyze(value)
  add_error_if_exceeds(record, attribute, res, max_level)
end