Skip to content

Commit

Permalink
fix(activemodel): ActiveModel::Errors#add accepts String and Proc for…
Browse files Browse the repository at this point in the history
… type

The behavior of passing String or Proc for type should be allowed.

FYI: It is documented in 6.1, but It is already available in 6.0.

cf. rails/rails@fcd1e41#diff-4deafad6fefcf6aa6626a1f7e3cd0ca1cf95e358f55a10a69e02be84d926bb31R368-R374

cf. rails/rails@d9011e3#diff-4deafad6fefcf6aa6626a1f7e3cd0ca1cf95e358f55a10a69e02be84d926bb31R370

Also, the name of the second argument was changed from `message` to `type` in 6.1.
  • Loading branch information
sanfrecce-osaka committed Nov 10, 2024
1 parent 34e19fc commit 0b39c22
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 1 deletion.
9 changes: 9 additions & 0 deletions gems/activemodel/6.0/_test/test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,17 @@ class Person

validates :name, presence: true, length: { maximum: 100 }
validates :email, presence: true, if: [:foo?, -> { age >= 20 }]
validate :should_be_satisfied_special_email_rule

def foo? = true

def should_be_satisfied_special_email_rule
if Time.current >= Time.zone.local(2024, 10)
errors.add(:email, -> (_person, _options) { "must be satisfied at least 3 rules after #{Time.zone.local(2024, 10)}" }) if [/a-z/, /A-Z/, /0-9/, /[+]/].count {|rule| email.match?(rule) } > 3
else
errors.add(:email, 'must be satisfied at least 2 rules') if [/a-z/, /A-Z/, /0-9/].count {|rule| email.match?(rule) } > 2
end
end
end

person = Person.new(name: 'John Doe')
Expand Down
1 change: 1 addition & 0 deletions gems/activemodel/6.0/_test/test.rbs
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ class Person
attr_accessor email: String

def foo?: () -> bool
def should_be_satisfied_special_email_rule: () -> void
end
2 changes: 1 addition & 1 deletion gems/activemodel/6.0/activemodel.rbs
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,6 @@ module ActiveModel
# # => {:base=>["either name or email must be present"]}
# person.errors.details
# # => {:base=>[{error: :name_or_email_blank}]}
def add: (untyped attribute, ?::Symbol message, ?::Hash[untyped, untyped] options) -> untyped
def add: (untyped attribute, ?::Symbol | ::String | ^(untyped base, ::Hash[untyped, untyped]) -> (::Symbol | ::String) type, ?::Hash[untyped, untyped] options) -> untyped
end
end

0 comments on commit 0b39c22

Please sign in to comment.