I was browsing the style guide when I found this recommendation.
If I remember correctly the advantage of using the scope DSL is that brings always a relation when the result may be empty, in order to chain the results. So I was a little puzzled by this recommendation.
Is there any specifics of why is this recommended?
@Cicloid I think you remember correctly. scope can chain even insides the block return nil, but that case usually involve conditional logic thatâs what we try to avoid in the block anyway. So I totally agree on style guide to use class methods instead.
scope :by_status, -> status { where(status: status) if status.present? }
# should be same in Rails 4
def self.by_status(status)
if status.present?
where(status: status)
else
all
end
end
I like to have my classes methods (Singleton or Instance) defined in code where it makes sense. I donât feel like the scope macro saves me much and it does cost me ctag compatibility and can easily hide growing complexity (in sheer number of methods defined). Additionally, there have historically been problems with the behavior of scope as compared to class methods.
An additional benefit of an âAlways use methodsâ guideline: You donât have to think about whether something is too complex for a scope macro. Itâs one more decision removed.