Skip to content

Instantly share code, notes, and snippets.

@patorash
Created May 30, 2016 03:02
Show Gist options
  • Save patorash/8f79c1dc9e271132a2152808b1bce477 to your computer and use it in GitHub Desktop.
Save patorash/8f79c1dc9e271132a2152808b1bce477 to your computer and use it in GitHub Desktop.
json type validator of ActiveRecord.
# Put this code in lib/validators/json_type_validator.rb
# Usage in your model:
# validates :json_attribute, json_type: true
#
# To have a detailed error use something like:
# validates :json_attribute, presence: true, json_type: {message: :some_i18n_key}
# In your yaml use:
# some_i18n_key: "detailed exception message: %{exception_message}"
#
# @see https://gist.github.com/joost/7ee5fbcc40e377369351
class JsonTypeValidator < ActiveModel::EachValidator
def initialize(options)
options.reverse_merge!(:message => :invalid)
super(options)
end
def validate_each(record, attribute, value)
value = record.try(:"#{attribute}_before_type_cast")
value = value.strip if value.is_a?(String)
return true if value.blank?
if value.is_a? String
ActiveSupport::JSON.decode(value)
else
true
end
rescue JSON::ParserError => exception
record.errors.add(attribute, options[:message], exception_message: exception.message)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment