ruby on rails - How to DRY scope methods used in two different classes? -
i using ruby on rails 3.2.2 , retrieve / scope associated objects "specifying" / "filtering on" attribute value on associated objects. is, @ time using following code:
class article < activerecord::base def self.search_by_title(search) where('articles.title ?', "%#{search}%") end end class articleassociation < activerecord::base def self.search_by_article_title(search) joins(:article).where('articles.title ?', "%#{search}%") end end
in above code where('articles.title ?', "%#{search}%")
clause repeated twice , thought may improved dry principle: is possible use the article.search_by_title
method directly in the articleassociation.search_by_article_title
method?
typical use cases are:
articleassociation.search_by_article_title("sample string")
article.search_by_title("sample string")
unless change code structure completely, no.
you hacking lambdas, more code code you're drying. there such thing refactoring, , such thing bad refactoring. unless piece of very complex or long code used in 2 or more places, can worry refactoring. code conventions important, tiny one-method-call things waste , make code more cryptic.
though, know it's annoying when people don't answer question, here:
class article < activerecord::base search_by_title=lambda {|obj, search| obj.where('articles.title ?', "%#{search}%")} def self.search_by_title(search) search_by_title.call(self, search) end end class articleassociation < activerecord::base def self.search_by_article_title(search) article::search_by_title.call(joins(:article),search) end end
that makes lambda constant performs where
call on specified object. both methods wrap lambda.
note: although may considered more elegant, decrease performance lot, lambdas, closures, , call expensive in dynamic language ruby. don't think that's issue you.
Comments
Post a Comment