Skip to content

Commit 1147658

Browse files
authored
Fix custom validator not ending with _validator (#2337)
* Remove ! Add spec * Changelog entry * Update Changelog's entry Update spec comment Add spec for anonymous class * Fix cop
1 parent d1dfdcc commit 1147658

File tree

3 files changed

+40
-1
lines changed

3 files changed

+40
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
#### Fixes
1414

1515
* [#2328](https://github.com/ruby-grape/grape/pull/2328): Don't cache Class.instance_methods - [@byroot](https://github.com/byroot).
16+
* [#2337](https://github.com/ruby-grape/grape/pull/2337): Fix: allow custom validators that do not end with _validator - [@ericproulx](https://github.com/ericproulx).
1617
* Your contribution here.
1718

1819
## 1.7.1 (2023/05/14)

lib/grape/validations/validators/base.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def validate!(params)
6464
def self.inherited(klass)
6565
return if klass.name.blank?
6666

67-
short_validator_name = klass.name.demodulize.underscore.delete_suffix!('_validator')
67+
short_validator_name = klass.name.demodulize.underscore.delete_suffix('_validator')
6868
Validations.register_validator(short_validator_name, klass)
6969
end
7070

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# frozen_string_literal: true
2+
3+
RSpec.describe Grape::Validations::Validators::Base do
4+
describe '#inherited' do
5+
context 'when validator is anonymous' do
6+
subject(:custom_validator) { Class.new(described_class) }
7+
8+
it 'does not register the validator' do
9+
expect(Grape::Validations).not_to receive(:register_validator)
10+
custom_validator
11+
end
12+
end
13+
14+
# Anonymous class does not have a name and class A < B would leak.
15+
# Simulates inherited callback
16+
context "when validator's underscored name does not end with _validator" do
17+
subject(:custom_validator) { described_class.inherited(TestModule::CustomValidatorABC) }
18+
19+
before { stub_const('TestModule::CustomValidatorABC', Class.new) }
20+
21+
it 'registers the custom validator with a short name' do
22+
expect(Grape::Validations).to receive(:register_validator).with('custom_validator_abc', TestModule::CustomValidatorABC)
23+
custom_validator
24+
end
25+
end
26+
27+
context "when validator's underscored name ends with _validator" do
28+
subject(:custom_validator) { described_class.inherited(TestModule::CustomValidator) }
29+
30+
before { stub_const('TestModule::CustomValidator', Class.new) }
31+
32+
it 'registers the custom validator with short name not ending with validator' do
33+
expect(Grape::Validations).to receive(:register_validator).with('custom', TestModule::CustomValidator)
34+
custom_validator
35+
end
36+
end
37+
end
38+
end

0 commit comments

Comments
 (0)