Sha256: e2adf9bc5294ff8493b347b75e01f1e0ee9c4facef87029f016d4467c49f7362

Contents?: true

Size: 1.18 KB

Versions: 1

Compression:

Stored size: 1.18 KB

Contents

class JsonValidator < ActiveModel::EachValidator
  def initialize(options)
    options.reverse_merge!(message: :invalid_json)
    options.reverse_merge!(schema: nil)
    @attributes = options[:attributes]

    super
  end

  # Redefine the setter method for the attributes, since we want to
  # catch any MultiJson::LoadError errors.
  def setup(model)
    @attributes.each do |attribute|
      model.class_eval <<-RUBY, __FILE__, __LINE__ + 1
        define_method "#{attribute}=" do |args|
          begin
            @_#{attribute}_sane_json = true
            super(args)
          rescue MultiJson::LoadError
            @_#{attribute}_sane_json = false
            super({})
          end
        end
      RUBY
    end
  end

  # Validate the JSON value with a JSON schema path or String
  def validate_each(record, attribute, value)
    begin
      json_value = JSON.dump(value)
    rescue JSON::GeneratorError
      json_value = ''
    end

    errors = ::JSON::Validator.fully_validate(options.fetch(:schema), json_value)

    if errors.any? || instance_variable_get(:"@_#{attribute}_sane_json") == false
      record.errors.add(attribute, options.fetch(:message), value: value)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
activerecord_json_validator-0.1.1 lib/active_record/json_validator/validator.rb