Feature #19708
openSupport `attr_reader :foo?`
Description
Creating reader methods with attr_reader
is preferable over defining them by hand, not only because it's more convenient, but also because it hits a fast path in MRI (see VM_METHOD_TYPE_IVAR
).
Since local and instance variables can't end with ?
, you can't use attr_reader
to define predicate-style methods for boolean values, like:
class Person
attr_reader :name, :age, :active? # invalid attribute name `active?' (NameError)
def initialize
@name = "Bob"
@age = 30
@active = true
end
end
It would be nice if attr_reader
(and friends) could behave like:
def active? = @active
(attr_writer
and attr_accessor
couldn't do the same, since def active?=(new_value)
isn't valid, so they'd probably stick with def active=(new_value)
)
Updated by AMomchilov (Alexander Momchilov) over 1 year ago
You can workaround this by using attr_reader
to create the optimized method, alias_method
to give it the nice active?
name, and then remove_method
to delete the original non-?
name:
module PredicateHelper # Or just monkey-patch Module, I won't sue :D
def define_predicate(predicate_name)
ivar_name = predicate_name.to_s.delete_suffix("?")
attr_reader(ivar_name)
alias_method(predicate_name, ivar_name)
remove_method(ivar_name)
end
end
Usage:
class Person
extend PredicateHelper
attr_reader :name, :age
define_predicate :active?
def initialize
@name = "Bob"
@age = 30
@active = true
end
end
bob = Person.new
p [bob.name, bob.age, bob.active?] # ["Bob", 30, true]
# Shows that `#active?` is just aliasing the now-deleted `#active`
p Person.instance_method(active?) # => #<UnboundMethod: Person#active?(active)() Untitled 2.rb:6>
Updated by AMomchilov (Alexander Momchilov) over 1 year ago
- Description updated (diff)
Updated by rubyFeedback (robert heiler) over 1 year ago
Personally I agree with the proposal, largely because I love methods that end with a trailing '?' - I think that was
a good language choice matz made to indicate query-like methods via ?.
Such as:
if game_over?
notify_the_user_that_the_game_is_over
end
I kind of have stopped using attr* methods though, in part because I could not use them for trailing '?', but
in part also because I seem to become lazier whenever I use attr methods. Additionally some methods need to
do some clean-up and sanitization steps in certain classes, and the attr-methods only really are super-simple,
not allowing for extra actions here - e. g. just to be used as setters and getters.
I do seem to remember that there was a reason given as to why no trailing '?' method exists for the attr-family
of methods. I think matz mentioned this once on the bugtracker, but I forgot the explanation. (You may have
hinted to this in your own proposal above, but I can not find matz' comment right now.)
You can workaround this by using attr_reader to create the optimized method, alias_method to give it the
nice active? name, and then remove_method to delete the original non-? name:
There are many workarounds. I simply use the "def" variant. :P
def age?
@age
end; alias age age?
(Although for larger classes, I shifted towards using a Hash that keeps track of all instance variables
instead. I found that once you have like ~20 different instance variables, a Hash seems easier to understand
than individual instance variables.)
Note that I think your proposal has not been clear in regards to what attr_reader would do.
Are these two separate methods or not? Consider this:
attr_reader :foobar
attr_reader :foobar?
Both would query over @foobar, right? But are these the same methods or different? e. g. when
someone undefines/removes them, is the other one removed or not? That should also be clarified
in the proposal IMO, just to make it instantly clear to the dev team what is meant exactly.
Updated by AMomchilov (Alexander Momchilov) over 1 year ago
You can workaround this by using attr_reader to create the optimized method, alias_method to give it the
nice active? name, and then remove_method to delete the original non-? name:There are many workarounds. I simply use the "def" variant. :P
def age? @age end; alias age age?
That's not equivalent. It's the "next best thing", but it creates a VM_METHOD_TYPE_ISEQ
method, not a more optimized VM_METHOD_TYPE_IVAR
.
Are these two separate methods or not? Consider this:
attr_reader :foobar attr_reader :foobar?
Both would query over @foobar, right?
Yep.
But are these the same methods or different? e. g. when
someone undefines/removes them, is the other one removed or not?
There's no ambiguity here, they're two different methods, that just happen to share an underlying instance variable, no different than if you had written them by hand:
def foobar
@foobar
end
def foobar?
@foobar
end
Their removal behaviour is obvious: you can remove one, or the other, or both. They're independent.
Updated by byroot (Jean Boussier) over 1 year ago
- Related to Feature #12046: Allow attr_reader :foo? to define instance method foo? for accessing @foo added
Updated by byroot (Jean Boussier) over 1 year ago
- Related to Feature #5781: Query attributes (attribute methods ending in `?` mark) added
Updated by byroot (Jean Boussier) over 1 year ago
This was proposed and rejected by Matz several time in the past (see the linked issues).
Not saying it's impossible to try again, but you'll likely need a much stronger case than that to convince Matz.
Updated by Eregon (Benoit Daloze) over 1 year ago
Agreed this would be nice and make such query methods more optimized.
In https://bugs.ruby-lang.org/issues/12046#note-3 it sounds to me matz was looking for a concrete use case, I think there are plenty in the wild.
I think a PR/patch for this would help to make progress (it might not be trivial).
Updated by AMomchilov (Alexander Momchilov) over 1 year ago
Hey Jean & Benoit, thanks for finding those prior discussions. I tried searching for them before posting, but the question mark makes it really hard to find anything relevant, haha
I think the use case is clear: defining reader methods that are both fast (VM_METHOD_TYPE_IVAR
) and idiomatic (#foo?
over #is_foo
).
Today you're forced to choose one or the other:
- Either you get idomatic naming with
def foo? = @foo
, but a slowerVM_METHOD_TYPE_ISEQ
method, - Or you get a faster method with
attr_reader :is_foo
, but lose the idomatic naming.
With the proposed change, you can get the best of both worlds.
There's also the case for convenience: you no longer have to split your attribute readers into two groups:
class C
attr_reader :a, :c, :d, :f # Group 1: non-predicate methods can use attr_reader
def initialize
# ...
end
# ... other stuff
# Group 2: predicate methods need explicit `def`s
def b? = @b
def e? = @e
end
I think a PR/patch for this would help to make progress (it might not be trivial).
I took a cursory look: I think it'll definitely be a challenge, but I think it's something to take on.
Ideally, I'd like to first get some sort of tentative interest, to make sure I don't put effort into a PR that's dead-on-arrival :D