Forked from carlosramireziii/attached_validator.rb
Created
September 23, 2018 23:24
-
-
Save RohitRox/01cc90099498ec597ef8c9a84546d38a to your computer and use it in GitHub Desktop.
A validator and RSpec matcher for requiring an attachment using Active Storage
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
class AttachedValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
record.errors.add(attribute, :attached, options) unless value.attached? | |
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
en: | |
activerecord: | |
errors: | |
messages: | |
attached: is not attached |
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
require "rspec/expectations" | |
RSpec::Matchers.define :validate_attachment_of do |attr_name| | |
match do |record| | |
matcher.matches?(record, attr_name) | |
end | |
chain :on do |validation_context| | |
matcher.on(validation_context) | |
end | |
chain :with_message do |message| | |
matcher.with_message(message) | |
end | |
private | |
def matcher | |
@matcher ||= ValidateAttachmentOfMatcher.new | |
end | |
class ValidateAttachmentOfMatcher | |
def on(validation_context) | |
@validation_context = validation_context | |
end | |
def with_message(message) | |
@message = message | |
end | |
def matches?(record, attr_name) | |
record.send(attr_name).purge | |
record.valid?(validation_context) | |
record.errors[attr_name].include? message | |
end | |
private | |
attr_reader :validation_context | |
def message | |
@message || I18n.translate("activerecord.errors.messages.attached") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment