Skip to content
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

Symbolize hash keys in a constructor #5

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter...
Filter file types
Jump to…
Jump to file or symbol
Failed to load files and symbols.

Always

Just for now

@@ -2,6 +2,7 @@

require 'dry/struct/version'
require 'dry/struct/errors'
require 'dry/struct/symbolize_keys'
require 'dry/struct/class_interface'
require 'dry/struct/hashify'
require 'dry/struct/value'
@@ -68,7 +68,7 @@ def new(attributes = default_attributes)
if attributes.instance_of?(self)
attributes
else
super(constructor[attributes])
super(constructor[SymbolizeKeys[attributes]])
end
rescue Types::SchemaError, Types::SchemaKeyError => error
raise Struct::Error, "[#{self}.new] #{error}"
@@ -0,0 +1,14 @@
# Symbolizes keys in a hash (at the top level, without nesting)

module Dry
class Struct
module SymbolizeKeys
def self.[](value)
return value unless value.respond_to?(:to_hash)
value.to_hash.each_with_object({}) do |(key, val), hash|
hash[key.to_sym] = val
end
end
end
end
end
@@ -46,6 +46,21 @@ class SuperUser < User
)
end

it 'accepts hashes with stringified keys' do
address = Test::Address.new('city' => 'NYC', 'zipcode' => '312')
user = user_type['name' => 'Jane', 'age' => 21, 'address' => address]

expect(user.address).to be(address)
end

it 'accepts any value that support #to_hash' do
address = double to_hash: { 'city' => 'NYC', 'zipcode' => '312' }
user = user_type[name: 'Jane', age: 21, address: address]

expect(user.address)
.to eq(Test::Address.new('city' => 'NYC', 'zipcode' => '312'))
end

it 'passes through values when they are structs already' do
address = Test::Address.new(city: 'NYC', zipcode: '312')
user = user_type[name: 'Jane', age: 21, address: address]
ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.