solnic / virtus

[DISCONTINUED ] Attributes on Steroids for Plain Old Ruby Objects
MIT License
3.77k stars 228 forks source link

Attribute default functionality not working #304

Closed duksis closed 9 years ago

duksis commented 9 years ago

it seems that the default option is not working

$ ruby --version
ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-darwin14.0]

$ gem list virtus

*** LOCAL GEMS ***

virtus (1.0.3)

$ ruby <<EOF
> require 'virtus'
> class User; end
> user = User.new
> user.extend Virtus.model
> user.attribute :name, String, default: 'John'
> puts user.name.inspect
> EOF
nil

Based on the readme I was expecting to have a default value for the attribute, but its nil.

solnic commented 9 years ago

That's actually an expected behavior. Default values are set in the constructor unless you use :lazy option to true. See:

irb(main):011:0> User = Class.new
=> User
irb(main):012:0> user = User.new
=> #<User:0x007ff6e9a12f88>
irb(main):013:0> mod = Virtus.model
=> #<Module:0x007ff6e9a7ce10>
irb(main):014:0> user.extend(mod)
=> #<User:0x007ff6e9a12f88 @attribute_set=#<Virtus::AttributeSet:0x007ff6e9a81ac8>>
irb(main):015:0> user.attribute :name, String, default: 'john', lazy: true
=> #<User:0x007ff6e9a12f88 @attribute_set=#<Virtus::AttributeSet:0x007ff6e9a81ac8>>
irb(main):016:0> user.name
=> "john"