virtus
virtus copied to clipboard
Hashie::Mash is coerced into Hash
Hi,
I am surprised that that Hashie::Mash is coerced into Hash.
Is this expected behavior? If so, how can I avoid it?
Thanks! :smiley:
Example:
require 'virtus'
require 'hashie'
class User
include Virtus.model
attribute :preferences, Hashie::Mash
end
preferences = Hashie::Mash.new({ foo: 1, bar: 2 })
puts "preferences = #{preferences.inspect}"
user = User.new(preferences: preferences)
puts "user.preferences = #{user.preferences.inspect}"
puts "user.preferences is a #{user.preferences.class}"
Output:
preferences = #<Hashie::Mash bar=2 foo=1>
user.preferences = {"foo"=>1, "bar"=>2}
user.preferences is a Hash
Have you tried making your own custom coercion? Or setting the coercion to that attribute to false?
attribute :preferences, Hashie::Mash, coerce: false
It is also possible that Hashie::Mash returns a hash class but with extended methods from Hashie::Mash.
Hi @magicalbanana,
Thanks for the comments!
coerce: false prevents the coercion, but I wonder if there are something that should be fixed.
What do you mean by "Hashie::Mash returns a hash class"? Do you have a specific name of a method on Hashie::Mash in mind?
@Domon I mean it is possible that Hashie::Mash's return class/object is a Hash class. You can look at whatever method you may be using to determine that. Look at Hashie's source code and see.
I am not too familiar with Hashie but I know it either returns a Hashie object which is a Hash eitherway. If you want to keep your coercion strict, you may want to look at custom value coercion with Virtus.