Introduce Hashie::Extensions::Dash::Coercion.

This commit is contained in:
Vladimir Kochnev 2015-08-28 19:12:56 +03:00
parent edeef5633c
commit 488c423c89
5 changed files with 70 additions and 0 deletions

View File

@ -2,6 +2,7 @@
* Your contribution here.
* [#304](https://github.com/intridea/hashie/pull/304): Ensured compatibility of `Hash` extensions with singleton objects - [@regexident](https://github.com/regexident).
* [#306](https://github.com/intridea/hashie/pull/306): Added Hashie::Extensions::Dash::Coercion - [@marshall-lee](https://github.com/marshall-lee).
## 3.4.2 (6/2/2015)

View File

@ -607,6 +607,36 @@ model.created_at.class #=> Time
To enable compatibility with Rails 4 use the [hashie-forbidden_attributes](https://github.com/Maxim-Filimonov/hashie-forbidden_attributes) gem.
### Dash Extension: Coercion.
If you want to use `Hashie::Extensions::Coercion` together with `Dash` then
you may probably want to use `Hashie::Extensions::Dash::Coercion` instead.
This extension automatically includes `Hashie::Extensions::Coercion`
and also adds a convenient `:coerce` option to `property` so you can define coercion in one line
instead of using `property` and `coerce_key` separate:
```ruby
class UserHash < Hashie::Dash
include Hashie::Extensions::Coercion
property :id
property :posts
coerce_key :posts, Array[PostHash]
end
```
This is the same as:
```ruby
class UserHash < Hashie::Dash
include Hashie::Extensions::Dash::Coercion
property :id
property :posts, coerce: Array[PostHash]
end
```
## Trash
A Trash is a Dash that allows you to translate keys on initialization. It mixes

View File

@ -34,6 +34,7 @@ module Hashie
module Dash
autoload :IndifferentAccess, 'hashie/extensions/dash/indifferent_access'
autoload :PropertyTranslation, 'hashie/extensions/dash/property_translation'
autoload :Coercion, 'hashie/extensions/dash/coercion'
end
module Mash

View File

@ -0,0 +1,25 @@
module Hashie
module Extensions
module Dash
module Coercion
# Extends a Dash with the ability to define coercion for properties.
def self.included(base)
base.send :include, Hashie::Extensions::Coercion
base.extend ClassMethods
end
module ClassMethods
# Defines a property on the Dash. Options are the standard
# <tt>Hashie::Dash#property</tt> options plus:
#
# * <tt>:coerce</tt> - The class into which you want the property coerced.
def property(property_name, options = {})
super
coerce_key property_name, options[:coerce] if options[:coerce]
end
end
end
end
end
end

View File

@ -0,0 +1,13 @@
require 'spec_helper'
describe Hashie::Extensions::Dash::Coercion do
class DashWithCoercion < Hashie::Dash
include Hashie::Extensions::Dash::Coercion
property :type, coerce: Symbol
end
it 'does the coercion of properties' do
expect(DashWithCoercion.new(type: 'something')).to eq(type: :something)
end
end