Sha256: fa2d844f0e6cab2fdc4a0234fcc31f3a08348a09be569ffa4cde13133c6debe8

Contents?: true

Size: 975 Bytes

Versions: 2

Compression:

Stored size: 975 Bytes

Contents

class JsonValidator < ActiveModel::EachValidator
  DEFAULT_SCHEMAS_PATH = %w(app models schemas).freeze

  def initialize(options)
    @model = options[:class]
    super
  end

  def validate_each(model, attribute, value)
    schema = options.fetch(:schema, default_schema(attribute))
    errors = JSON::Validator.fully_validate(schema, value)
    model.errors.add(attribute, message(errors)) if errors.any?
  end

  private

  def message(errors)
    message = options.fetch(:message, :invalid_json)
    return message unless message.respond_to?(:call)
    message.call(errors)
  end

  def default_root_path
    Rails.root.join.to_s if defined?(Rails)
    File.join.to_s
  end

  def default_schemas_path
    DEFAULT_SCHEMAS_PATH
  end

  def default_model_path
    @model.model_name.singular
  end

  def default_schema(attribute)
    File.join(
      default_root_path,
      default_schemas_path,
      default_model_path,
      "#{attribute}.json"
    ).to_s
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
activemodel_json_validator-0.1.1 lib/active_model/json_validator/validator.rb
activemodel_json_validator-0.1.0 lib/activemodel/json_validator/validator.rb