voltrb / volt

A Ruby web framework where your Ruby runs on both server and client
MIT License
3.22k stars 196 forks source link

How to use Volt::Boolean? #341

Open myknbani opened 8 years ago

myknbani commented 8 years ago

I have the following field definitions in my User class:

field :admin, Volt::Boolean

And for my user_seeds.rb file I have

store = Volt.current_app.store

user = store._users.buffer
# ... 
user.admin = true
puts user.save!.inspect

When I run it produces:

$ be volt runner app/main/seeds/user_seeds.rb 
Volt 0.9.6
D, [2015-12-30T17:59:34.178567 #21447] DEBUG -- : MONGODB | Adding localhost:27017 to the cluster.
#<Promise(47272688869560): #<Volt::Errors {:admin=>["must be true or false"]}>>

The following seems to do what I want:

field :admin, [TrueClass, FalseClass]

afaur commented 8 years ago

Hello @myknbani

Thanks for opening this issue, I do not know the answer to your question and it is not extremely clear to me either. I saw the only example I could find of it here (https://github.com/voltrb/docs/blob/7a496e81ed547407fb57ef62eedf0c655afa27f5/en/docs/models.md#fields) which does not show it being populated via seeding.

If someone could chime in here on this it would be much appreciated. Here are some points of interest in the code regarding Volt::Boolean..

https://github.com/voltrb/volt/blob/eae99c12c0b6cda5730303edefd3bc4da5d406f4/lib/volt/models/validators/type_validator.rb

https://github.com/voltrb/volt/blob/eae99c12c0b6cda5730303edefd3bc4da5d406f4/lib/volt/utils/boolean_patch.rb

https://github.com/voltrb/volt/blob/eae99c12c0b6cda5730303edefd3bc4da5d406f4/spec/models/validators/type_validator_spec.rb#L45

@myknbani Would you mind putting up on github an example project that reproduces this issue so that it can be easily investigated further? I am sure that would help other people interested in determining what they need to do to implement the desired behavior.

myknbani commented 8 years ago

@afaur Thanks for chiming in.

I think it's because of

if value.is_a?(type_rest)

true.is_a?(Volt::Boolean) is false.

A quick tinkering with the Volt console shows this issue:

[2] volt(main)> class Foo < Volt::Model
[2] volt(main)*   field :cute, Volt::Boolean
[2] volt(main)* end  
=> :cute=

[3] volt(main)> f = store._foos.buffer(cute: true)
=> #<Foo id: "5885..657b", cute: true>

[4] volt(main)> f.validate!
=> #<Promise(47396377599140): #<Volt::Errors {:cute=>["must be true or false"]}>>

[5] volt(main)> class Bar < Volt::Model
[5] volt(main)*   field :evil, [TrueClass, FalseClass]
[5] volt(main)* end  
=> :evil=

[6] volt(main)> b = store._bars.buffer(evil: false)
=> #<Bar id: "f6d5..5c94", evil: false>

[7] volt(main)> b.validate!
=> #<Promise(47396380736960): #<Volt::Errors {}>>