Logic duplication in scopes & predicates

23 views
Skip to first unread message

f...@excursiopedia.com

unread,
Sep 15, 2014, 10:03:56 PM9/15/14
to rubyonra...@googlegroups.com
Consider something like that in a model:

scope :recommended, -> { where('editors_selection OR rating > 9') }

def recommended?
  
editors_selection? || rating > 9
end

How to DRY it up?

Vivek Sampara

unread,
Sep 16, 2014, 4:03:42 AM9/16/14
to rubyonra...@googlegroups.com
scope :recommended, -> { where(recommended_condition) }

def recommended?
  eval(recommended_condition("||"))
end

def recommended_condition(selector = "OR")
  "editors_selection #{selector} rating > 9"
end


--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-ta...@googlegroups.com.
To post to this group, send email to rubyonra...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/86dabc42-3b35-4cbe-ae55-032a371276e5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Vivek Sampara

unread,
Sep 16, 2014, 4:04:56 AM9/16/14
to rubyonra...@googlegroups.com
tiny update - 



scope :recommended, -> { where(self.recommended_condition) }

def recommended?
  eval(self.class.recommended_condition("||"))
end

def self.recommended_condition(selector == "OR")
  'editors_selection #{selector} rating > 9'
end
Reply all
Reply to author
Forward
0 new messages