Skip to content

Conversation

@sidane
Copy link
Collaborator

@sidane sidane commented Oct 3, 2025

attr_evaluated can be used to define an attribute who's return value is evaluated/computed at runtime.

It defines a normal writer method using attr_writer which can take either a static value or a proc/lambda.

If the latter, the reader method will evaluate the proc/lambda when called and return its value. This allows for defining dynamic runtime behaviour for specific record attributes.

A static value can still be assigned like other non-evaluated attributes, and that value will always be returned.

E.g.

class MyClass
  include StaticAssociation

  attr_accessor :toggle
  attr_evaluated :status

  record(id: 1) do
    self.toggle = true
    self.status = -> { toggle ? "on" : "off" }
  end

  record(id: 2) do
    self.toggle = true
    self.status = "static value"
  end
end

record1 = MyClass.find(1)
record1.status # => "on"

record2 = MyClass.find(2)
record2.status # => "static value"

As with attr_accessor you can pass multiple attribute names to a single attr_evaluated call.

attr_evaluated :my_attr_1, :my_attr_2

`attr_evaluated` can be used to define an attribute who's return value
is evaluated/computed at runtime.

It defines a normal writer method using `attr_writer` which can take
either a static value or a proc/lambda.

If the latter, the reader method will evaluate the proc/lambda when
called and return its value. This allows for defining dynamic runtime
behaviour for specific record attributes.

A static value can still be assigned like other non-evaluated
attributes, and that value will always be returned.

E.g.

```ruby
class MyClass
  include StaticAssociation

  attr_accessor :toggle
  attr_evaluated :status

  record(id: 1) do
    self.toggle = true
    self.status = -> { toggle ? "on" : "off" }
  end

  record(id: 2) do
    self.toggle = true
    self.status = "static value"
  end
end

record1 = MyClass.find(1)
record1.status # => "on"

record2 = MyClass.find(2)
record2.status # => "static value"
```

As with `attr_accessor` you can pass multiple attribute names to a
single `attr_evaluated` call.

```ruby
attr_evaluated :my_attr_1, :my_attr_2
```
@sidane sidane merged commit c5dfb9b into main Oct 24, 2025
10 checks passed
@sidane sidane deleted the evaluated-attributes branch October 24, 2025 14:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants