Proposal: Predicate methods for CurrentAttributes

Hi all :wave:,

I found myself consistently writing this pattern so I figured it might be a useful feature to add:

# Currently ...
if Current.user == @user
  do_thing
else 
  complain!
end
# Proposed ...
if Current.user?(@user) #=> true
  do_thing
else 
  complain!
end

I’ve prepared a draft of this update on my own fork. For convenience, I also added support for:

Current.user? # => false
Current.user = User.find(1)
Current.user? # => true

Link here: Add predicate methods for CurrentAttributes · rails/rails@dd818ba · GitHub

Feedback welcome!

Thank you for the suggestion but I think this can be done using a method in the Current class itself you created or a private method in the place you are checking for the current user.

class Current < ActiveSupport::CurrentAttributes
  def user?(other)
    user == other
  end
end

I don’t think we need to increase the complexity of this object more for something that is so easy to define.

4 Likes

I think the way to implement as Current#user? is better. because of TDA principle.

1 Like

Thanks for your feedback, Rafael.

I understand your point, that devs can simply write any convenience predicate methods that they need.

It seemed to me that this pattern is fairly common in Rails (ActiveRecord and ActiveModel both provide convenience methods for each attribute—many of which are never used in practice).

Is there any online guidance for how these feature suggestions are evaluated by the Rails team?

I understand there are convenience methods spread across the entire framework, but that doesn’t mean we should accept all the new convenience methods people want to add.

It boils down to maintenance cost vs usefulness of the feature. The cost here is not huge, but the boilerplate this new convenience will avoid is also not huge, so in my opinion it is better to not add.

Other core members might disagree and want to merge, and they follow the topics here, and so far we had no interest in this thread.