Reputation: 2221
I have a short question on ruby / rails method naming conventions or good practice. Consider the following methods:
# some methods performing some sort of 'action'
def action; end
def action!; end
# some methods checking if performing 'action' is permitted
def action?; end
def can_action?; end
def action_allowed?; end
So I wonder, which of the three ampersand-methods would be the "best" way to ask for permissions. I would go with the first one somehow, but in some cases I think this might be confused with meaning has_performed_action?
.
So the second approach might make that clearer but is also a bit more verbose. The third one is actually just for completeness. I don't really like that one.
So are there any commonly agreed-on good practices for that?
Upvotes: 3
Views: 5827
Reputation: 7786
I'd go up one level and rethink the original method names. If the methods perform an action, then the role they play is that of a verb, not a noun:
# some methods performing some sort of 'action'
def act
def act!
This has the handy side effect of a more natural-sounding answer to your question:
# method checking if 'action' is permitted
def can_act?
...as well as some other obvious variants:
# methods checking if 'action' was performed
def acted?
def did_act?
# method checking if 'action' is called for by other circumstances
def should_act?
# method putting 'action' into a work queue
def act_later(delay_seconds=0)
Et cetera.
Upvotes: 0
Reputation: 34350
I think that depends on the action you want to perform and the action you are checking for. I would aim for readability and least amount of confusion:
self.run
self.can_run? # can this object run?
self.running_allowed? # is running allowed here or by this user?
self.redeem!
self.redeemable? # is this object currently redeemable?
self.copy_to_clipboard
self.copy_to_dashboard
self.copyable? or self.can_be_copied? #can this object be copied
self.copy_allowed?(:clipboard) # is copying to the clipboard allowed by me?
Upvotes: 6
Reputation: 62688
I wouldn't use action?
, because typically, single-word question-mark methods are used to indicate the presence (or absence) of a value. Rails lets you write English-like code, so pick a method name that makes the code the most readable.
perform_action!("update") if action_allowed?("update")
Seems perfectly readable to me.
Upvotes: 2