【发布时间】:2019-07-28 22:31:09
【问题描述】:
我有一个自定义的EachValidator,用于两种不同的模型。我将其移至关注点以干燥模型:
module Isbn
extend ActiveSupport::Concern
included do
class IsbnValidator < ActiveModel::EachValidator
GOOD_ISBN = /^97[89]/.freeze
def validate_each(record, attribute, value)
# snip...
end
end
end
end
class Book < ApplicationRecord
include Isbn
validates :isbn, allow_nil: true, isbn: true
end
class BookPart < ApplicationRecord
include Isbn
validates :isbn, allow_nil: true, isbn: true
end
在运行 Rails 时(在本例中是通过 RSpec),我收到以下警告:
$ bundle exec rspec
C:/Users/USER/api/app/models/concerns/isbn.rb:16: warning: already initialized constant Isbn::IsbnValidator::GOOD_ISBN
C:/Users/USER/api/app/models/concerns/isbn.rb:16: warning: previous definition of GOOD_ISBN was here
有什么办法可以避免它并在每个模型中干净地包含验证器?
【问题讨论】:
标签: ruby-on-rails ruby activesupport activesupport-concern