Can I use an ActiveRecord scope as an instance method?

JD Huntington picture JD Huntington · Apr 25, 2014 · Viewed 10.4k times · Source

I have a scope that acts as a filter. For instance:

class User
  scope :in_good_standing, -> { where(:some_val => 'foo', :some_other_val => 'bar' }
end

Because in_good_standing depends on more than one condition, I'd like to have this defined on an instance of User as:

def in_good_standing?
  some_val == 'foo' && some_other_val == 'bar'
end

However, I'd really like to avoid duplicating the logic between both the instance method and the named scope. Is there a way to define #in_good_standing? in a way that simply refers to the scope?

edit

I realize these are very different concepts (one is a class method, one is an instance method), hence my question. As @MrDanA mentioned in a comment, the closest I can get is to check whether or not the record I'm curious about exists within the larger scope, which is probably the answer I'm looking for.

The responses about separating out different scopes from my example are useful, but I'm looking for a general pattern to apply to an application with some very complicated logic being driven by scopes.

Answer

Pavan picture Pavan · Apr 25, 2014

Scopes are nothing but class methods.You can define it like this

def self.in_good_standing?
  #your logic goes here
end