Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions lib/permittable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1621,7 +1621,11 @@ def authored_nil!(field, opt)
def validate_message!(field)
spec = field[:message]
return if spec.nil?
return if spec.is_a?(String)

if spec.is_a?(String)
field[:message] = freeze_authored(spec)
return
end

valid_hash = spec.is_a?(Hash) && !spec.empty? &&
spec.all? { |code, text| (code.is_a?(Symbol) || code.is_a?(String)) && text.is_a?(String) }
Expand All @@ -1630,7 +1634,7 @@ def validate_message!(field)
"or a Hash of violation code => String (e.g. { missing: \"is required\" })"
end

field[:message] = spec.transform_keys(&:to_sym).freeze
field[:message] = freeze_authored(spec.transform_keys(&:to_sym))
end
end

Expand Down
14 changes: 14 additions & 0 deletions spec/field_group_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -196,5 +196,19 @@ def controller(klass, params: {}, action: "create")
permittable_class { permit_params(:create) { use group } }
expect(Permittable.filter_parameter_registry.include?("ssn")).to be(true)
end

it "freezes a shared field's message: so mutating one contract's violation can't corrupt another's" do
group = Permittable.fields { required :age, :integer, message: { missing: "age please" } }
contract_a = Permittable::Contract.define { use group }
contract_b = Permittable::Contract.define { use group }

msg = contract_a.call({}).violations.first[:message]
expect(msg).to eq("age please")
expect { msg << " NOW" }.to raise_error(FrozenError)

msg_b = contract_b.call({}).violations.first[:message]
expect(msg_b).to eq("age please")
expect(msg_b).to equal(msg) # same shared object — proves it stayed intact, not just re-fetched
end
end
end
Loading