Greg
Greg

Reputation: 6649

What is the idiomatic way to use current_scope or create a new one in model's class method

I want to use to_csv method in a chain like this Company.where(created_at: '2010-01-01').limit(20).to_csv

To do so, I use current_scope and it works fine. But when calling the same method like this Company.to_csv it complains because current_scope is nil.

Right now I'm using (current_scope || where(true)) which does the trick for me, but maybe there's a "proper" way to do it?

  def self.to_csv
    CSV.generate do |csv|
      (current_scope || where(true)).includes(:_address).each do |company|
        csv << company.attributes
      end
    end
  end

Ps. I know I could just use current_scope and call Company.all.to_csv, but this is not what's this question is about.

Upvotes: 3

Views: 1194

Answers (1)

rubyprince
rubyprince

Reputation: 17803

I know I am late to the party. I was trying to find the method corresponding to current_scope and stumbled upon your question (and found my precious current_scope method, so thank you).

I think for your case, you could have just written:

def self.to_csv
  CSV.generate do |csv|
    includes(:_address).each do |company|
      csv << company.attributes
    end
  end
end

You dont have to use current_scope method as Rails already does that for you.

If you are wondering why I had to go looking for current_scope, I had to chain to current_scope like an n number of times, see this:

def self.search(terms)
  terms = Array(terms)
  return all if terms.blank?
  filtered = current_scope || all
  terms.each do |term|
    filtered = filtered.search_scope(term)
  end
  filtered
end

def self.search_scope(term)
  # logic for scope on 1 term 
  # returns a scope
end

So I could call like this: MyModel.search(['test1', 'test2']).limit(5) or MyModel.limit(5).search('test')

Upvotes: 1

Related Questions