Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use an ActiveRecord scope as an instance method?

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.

like image 409
JD Huntington Avatar asked Apr 25 '14 18:04

JD Huntington


1 Answers

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

def self.in_good_standing?
  #your logic goes here
end
like image 121
Pavan Avatar answered Sep 24 '22 10:09

Pavan