PoC: Optimize predicate methods with attr_reader#5082
PoC: Optimize predicate methods with attr_reader#5082amomchilov wants to merge 1 commit intormosolgo:masterfrom
attr_reader#5082Conversation
| attr_reader :abstract | ||
| alias_method :abstract?, :abstract | ||
| remove_method :abstract |
There was a problem hiding this comment.
It's also possible to make a helper to automate these, but then IDEs won't know about the presence of the generated methods.
module PredicateHelper # This can be mixed into Module, if you're into monkey-patching
# Given `"foo?"`, this method generates an optimized method that reads from `@foo`.
def attr_predicate(predicate_name)
raise ArgumentError unless predicate_name.end_with?("?")
attr_method_name = predicate_name.to_s.delete_suffix("?")
attr_reader(attr_method_name)
alias_method(predicate_name, attr_method_name)
remove_method(attr_method_name)
end
end|
Hey, thanks for proposing this change! I'm definitely interested in it. Another implementation might be write a Rubocop rule which identifies and updates code that uses the "bad" approach. There are a couple other development-related cops here in case you're interested in try that: https://github.com/rmosolgo/graphql-ruby/tree/master/cop/development |
|
@rmosolgo Happy to hear! This is definitely rubocop-able. I'd even go so far as to add it upstream to https://github.com/rubocop/rubocop-performance Would you mind running a quick benchmark on this, to see if it's worthwhile? Btw I wrote up more details in the issue: #5081 I have some env issues, and I won't have time to sort them out until at least next week |
PoC for #5081