ruby / rails布尔方法命名约定

时间:2011-02-09 23:00:11

标签: ruby-on-rails ruby methods naming-conventions

我有一个关于ruby / rails方法命名约定或良好实践的简短问题。 请考虑以下方法:

# 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

所以我想知道,三种&符号方法中哪一种是寻求权限的“最佳”方式。我会以某种方式使用第一个,但在某些情况下,我认为这可能与意义has_performed_action?混淆。 因此,第二种方法可能会更清晰,但也更冗长。第三个实际上只是为了完整性。我真的不喜欢那个。

那么有没有共同商定的良好做法?

4 个答案:

答案 0 :(得分:4)

我认为这取决于您要执行的操作以及您要检查的操作。我的目标是可读性和最少的混淆:

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?

答案 1 :(得分:2)

我不会使用action?,因为通常使用单字问号方法来指示值的存在(或不存在)。 Rails允许您编写类似英语的代码,因此选择一个使代码最具可读性的方法名称。

perform_action!("update") if action_allowed?("update")

对我来说似乎完全可读。

答案 2 :(得分:1)

我上升一级并重新考虑原始方法名称。如果方法执行动作,那么它们扮演的角色是动词,而不是名词:

# some methods performing some sort of 'action'
def act
def act!

这对你的问题有一个更自然的答案的方便的副作用:

# method checking if 'action' is permitted
def can_act?

......以及其他一些明显的变体:

# 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)

等等。

答案 3 :(得分:0)

def can_action?; end
相关问题