Skip to content

Commit d94892f

Browse files
author
atwam
committed
Evaluate normalization block in the context of the object
1 parent 7e39313 commit d94892f

File tree

4 files changed

+12
-1
lines changed

4 files changed

+12
-1
lines changed

lib/attribute_normalizer/model_inclusions.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def normalize_attributes(*attributes, &block)
3030
normalized = normalizer.respond_to?(:normalize) ? normalizer.normalize( normalized , options) : normalizer.call(normalized, options)
3131
end
3232

33-
normalized = block_given? ? yield(normalized) : normalized
33+
normalized = block_given? ? instance_exec(normalized, &block) : normalized
3434

3535
if block_given?
3636
post_normalizers.each do |normalizer_name|

spec/connection_and_schema.rb

+2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@
77
ActiveRecord::Schema.define do
88
create_table :publishers, :force => true do |t|
99
t.string :name
10+
t.string :country
1011
t.string :phone_number
12+
t.string :international_phone_number
1113
end
1214

1315
create_table :authors, :force => true do |t|

spec/models/publisher.rb

+4
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,8 @@ def name=(_)
1010
normalize_attribute :name, :with => :blank
1111
normalize_attribute :phone_number, :with => :phone
1212

13+
normalize_attribute :international_phone_number do |number|
14+
self.country == 'fr' ? number.sub(/^0/,'+33') : number
15+
end
16+
1317
end

spec/publisher_spec.rb

+5
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@
88
it { should normalize_attribute(:phone_number).from('+ 1 (877) 987-9875').to('18779879875') }
99
end
1010

11+
context 'access to object in normalizer block' do
12+
subject { Publisher.new(:country => 'fr') }
13+
it { should normalize_attribute(:international_phone_number).from('0612345678').to('+33612345678') }
14+
end
15+
1116
context 'on custom writer method' do
1217
subject { Publisher.new(:name => 'Mike') }
1318
it { should normalize_attribute(:name).from('').to(nil) }

0 commit comments

Comments
 (0)