Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Changed before filters to return (i.e. be able to modify) the input r…

…ather than the output
  • Loading branch information...
commit c502e79423b5736437df9efed83a2dc68a419d9f 1 parent 36c5ebe
@markevans markevans authored
Showing with 9 additions and 8 deletions.
  1. +3 −3 README.rdoc
  2. +1 −1  lib/hash_mapper.rb
  3. +5 −4 spec/hash_mapper_spec.rb
View
6 README.rdoc
@@ -201,8 +201,8 @@ They all yield a block with 2 arguments - the hash you are mapping from and the
map from('/raw'), to('/fried')
before_normalize do |input, output|
- output[:time] = Time.now # the normalized hash will now be {:fried => 'blah', :time => <time object> }
- output
+ input['raw'] ||= 'please' # this will give 'raw' a default value
+ input
end
after_denormalize do |input, output|
@@ -211,7 +211,7 @@ They all yield a block with 2 arguments - the hash you are mapping from and the
end
-Important: note that you need to return the output each time.
+Important: note that for before filters, you need to return the (modified) input, and for after filters, you need to return the output.
Note also that 'output' is correct at the time of the filter, i.e. before_normalize yields 'output' as an empty hash, while after_normalize yields it as an already normalized hash.
View
2  lib/hash_mapper.rb
@@ -64,7 +64,7 @@ def perform_hash_mapping(a_hash, meth)
output = {}
# Before filter
before_filter = instance_eval "@before_#{meth}"
- output = before_filter.call(a_hash, output) if before_filter
+ a_hash = before_filter.call(a_hash, output) if before_filter
# Do the mapping
a_hash = symbolize_keys(a_hash)
maps.each do |m|
View
9 spec/hash_mapper_spec.rb
@@ -296,14 +296,15 @@ class NoKeys
class WithBeforeFilters
extend HashMapper
map from('/hello'), to('/goodbye')
+ map from('/extra'), to('/extra')
before_normalize do |input, output|
- output[:this_is] = "extra #{input[:hello]} innit"
- output
+ input[:extra] = "extra #{input[:hello]} innit"
+ input
end
before_denormalize do |input, output|
input[:goodbye] = 'changed'
- output
+ input
end
end
@@ -327,7 +328,7 @@ class WithAfterFilters
@norm = {:goodbye => 'seeya later!'}
end
it "should allow filtering before normalize" do
- WithBeforeFilters.normalize(@denorm).should == {:goodbye => 'wassup?!', :this_is => 'extra wassup?! innit'}
+ WithBeforeFilters.normalize(@denorm).should == {:goodbye => 'wassup?!', :extra => 'extra wassup?! innit'}
end
it "should allow filtering before denormalize" do
WithBeforeFilters.denormalize(@norm).should == {:hello => 'changed'}
Please sign in to comment.
Something went wrong with that request. Please try again.