Skip to content

Evaluate normalization block in the context of the object #75

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 5, 2020
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
2 changes: 1 addition & 1 deletion lib/attribute_normalizer/model_inclusions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def normalize_attributes(*attributes, &block)
normalized = normalizer.respond_to?(:normalize) ? normalizer.normalize( normalized , options) : normalizer.call(normalized, options)
end

normalized = block_given? ? yield(normalized) : normalized
normalized = block_given? ? instance_exec(normalized, &block) : normalized

if block_given?
post_normalizers.each do |normalizer_name|
Expand Down
2 changes: 2 additions & 0 deletions spec/connection_and_schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
ActiveRecord::Schema.define do
create_table :publishers, :force => true do |t|
t.string :name
t.string :country
t.string :phone_number
t.string :international_phone_number
end

create_table :authors, :force => true do |t|
Expand Down
4 changes: 4 additions & 0 deletions spec/models/publisher.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,8 @@ def name=(_)
normalize_attribute :name, :with => :blank
normalize_attribute :phone_number, :with => :phone

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

end
5 changes: 5 additions & 0 deletions spec/publisher_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@
it { should normalize_attribute(:phone_number).from('+ 1 (877) 987-9875').to('18779879875') }
end

context 'access to object in normalizer block' do
subject { Publisher.new(:country => 'fr') }
it { should normalize_attribute(:international_phone_number).from('0612345678').to('+33612345678') }
end

context 'on custom writer method' do
subject { Publisher.new(:name => 'Mike') }
it { should normalize_attribute(:name).from('').to(nil) }
Expand Down