Last active
January 19, 2017 14:11
-
-
Save mhulet/4d5a3c0f53227e64aae4c90a09431c75 to your computer and use it in GitHub Desktop.
Liquid syntax validator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/application.rb | |
# ... | |
module AppName | |
# ... | |
config.autoload_paths << Rails.root.join("validators") | |
# ... | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/message.rb | |
class Message < ActiveRecord::Base | |
validates :content, liquid: true | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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