Skip to content

Instantly share code, notes, and snippets.

@mhulet
Last active January 19, 2017 14:11
Show Gist options
  • Save mhulet/4d5a3c0f53227e64aae4c90a09431c75 to your computer and use it in GitHub Desktop.
Save mhulet/4d5a3c0f53227e64aae4c90a09431c75 to your computer and use it in GitHub Desktop.
Liquid syntax validator
# config/application.rb
# ...
module AppName
# ...
config.autoload_paths << Rails.root.join("validators")
# ...
end
# app/validators/liquid_validator.rb
class LiquidValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
Liquid::Template.parse(value)
rescue Liquid::SyntaxError => e
record.errors.add(attribute, e.message)
end
end
# app/models/message.rb
class Message < ActiveRecord::Base
validates :content, liquid: true
end
# spec/models/message_spec.rb
require 'rails_helper'
RSpec.describe Message, type: :model do
describe 'Liquid validation' do
subject { build :message }
it 'allows valid content' do
subject.content = 'Hi {{ firstname }}!'
subject.valid?
expect(subject).to be_valid
end
it 'adds an error for invalid content' do
subject.content = '{{ firstname, how are you today?'
subject.valid?
expect(subject).not_to be_valid
expect(subject.errors).to have_key(:content)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment