davydovanton / shallow_attributes

Simple and lightweight Virtus analog.
MIT License
101 stars 18 forks source link

Initializer can take stringified hashes #9

Closed tatey closed 7 years ago

tatey commented 7 years ago

This patch makes ShallowAttributes work out of the box with ActionController::StrongParameters. The motivations for this patch are:

  1. ShallowAttributes expects to work with symbolized hashes, but parameters in Rails are stringified hashes.
  2. The initializer was mutating the hash. When I passed it to another object, it was missing key-value pairs. This tripped me up for a good 10 minutes.

We were working around 2 by calling params.to_h.symbolize_keys before passing it to the initializer. This made the API feel a little rough and gave me the motivation to write this patch.

You'll notice I used #each_pair over #each_with_object or #reduce. This is the only public method that is available on both Hash and ActionController::StrongParameters which lets us symbolize the hash.

I'm aware you may be opposed to the patch because it creates a new object and uses #each_pair. If you are opposed then I am open to exploring other options to make a great out of the box Rails experience.

Either way let me know. All feedback welcome.

Cheers, Tate

coveralls commented 7 years ago

Coverage Status

Coverage increased (+0.02%) to 99.098% when pulling a9e28c77ad5c95ee07e935a49817544b74013796 on tatey:stringified-hash into 3740a540e457b48e4867781039ab44fad14e10d1 on davydovanton:master.

davydovanton commented 7 years ago

Thanks for contribution!