0

Using dry-rb structs and types, I'm trying amend an object that has already been created, but can't seem to figure it out.

[3] pry(main)> class User < Dry::Struct
  attribute :name, Types::String.optional
  attribute :age, Types::Coercible::Integer
end
=> User
[4] pry(main)> user = User.new(name: nil, age: '21')
=> #<User name=nil age=21>
[5] pry(main)> user.name = "ted"
NoMethodError: undefined method `name=' for #<User name=nil age=21>
Did you mean?  name
from (pry):10:in `__pry__'
[6] pry(main)> user(name: "Ted")
NoMethodError: undefined method `user' for main:Object
Did you mean?  super
from (pry):11:in `__pry__'
[7] pry(main)> user[:name => "Ted"]
Dry::Struct::MissingAttributeError: Missing attribute: {:name=>"Ted"}
from /Users/me/.rvm/gems/ruby-2.6.5/gems/dry-struct-1.3.0/lib/dry/struct.rb:137:in `block in []'
[8] pry(main)> user('name' => 'Ted')
NoMethodError: undefined method `user' for main:Object
Did you mean?  super
from (pry):13:in `__pry__'

Is this just not possible, or am I missing something super obvious? Any help is much appreciated

magicfishy
  • 90
  • 8
  • 2
    It is not possible since objects should be treated as immutable. Check https://github.com/dry-rb/dry-types/issues/106. – yzalavin Feb 02 '21 at 18:53
  • 2
    Just like @yzalavin mentioned: https://dry-rb.org/gems/dry-struct/1.0/#differences-between-dry-struct-and-virtus (first bullet point) If you really wanted to do this you could `User.new(user.to_h.merge(name: 'Ted'))` or `user.attributes.merge!(name:'Ted')` – engineersmnky Feb 02 '21 at 18:55
  • Got it - totally missed that. Thank you both! – magicfishy Feb 02 '21 at 18:57

0 Answers0