with_scope is protected

I’ve seen a lot of people run into trouble using with_scope on edge. It’s now a protected method Ticket: http://dev.rubyonrails.org/ticket/8524.

The solution? Don’t use it or use it sparingly. They made it protected for a reason – to protect people from abusing it – but if you absolutely must have at it then you can do something like this:

   klass.send(:with_scope, :find => { :conditions => conditions }) { yield }

So say you want to scope your finders to retrieve only MyModel objects of type ‘super’:

  def my_super_duper_scoping(klass)    klass.send(:with_scope, :find => { :conditions => "type = 'super'" }) { yield }  end    my_super_models = my_super_duper_scoping(MyModel) do      MyModel.find(:all)    end    my_super_models_named_david = my_super_duper_scoping(MyModel) do      MyModel.find(:all, :conditions => ["name = '?'", 'david')    end

Using self.class.send is a way to get around public and private checking in ruby 1.8. Use with caution.