Ruby - dry-rb - how to update an existing object's attributes?

1.8k views Asked by At

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

0

There are 0 answers