70089e712ed13abb99bec89bd5bfba77

i dont find a better way to do this, and i dont like the first attribution line, anybody haz a better idea? tnx

def self.all_leaves
    leaves = []
    Category.roots.each do |category|
      leaves << category.children
    end
    leaves.flatten
  end

Refactorings

No refactoring yet !

D41d8cd98f00b204e9800998ecf8427e

bob

July 23, 2009, July 23, 2009 23:56, permalink

1 rating. Login to rate!
def self.all_leaves
    Category.roots.collect { |category| category.children }.flatten
  end

# or

  def self.all_leaves
    Category.roots.inject([]) { |acc, category| acc + category.children }
  end
D41d8cd98f00b204e9800998ecf8427e

Kett

July 24, 2009, July 24, 2009 00:00, permalink

1 rating. Login to rate!

This should work...

def self.all_leaves
  Category.roots.inject([]) { |result,category| result.concat(category.children) }
end
D41d8cd98f00b204e9800998ecf8427e

steved

July 24, 2009, July 24, 2009 19:00, permalink

1 rating. Login to rate!
# if you have Symbol#to_proc

def self.all_leaves
  Category.roots.map(&:children).flatten
end
F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

July 24, 2009, July 24, 2009 21:00, permalink

1 rating. Login to rate!

If you have the 'every' gem:

def self.all_leaves
  Category.roots.every.children.flatten
end
D85d44a0eca045f40e5a31449277c26c

Ben Marini

September 21, 2009, September 21, 2009 02:16, permalink

No rating. Login to rate!

I'm assuming this is ActiveRecord, and each call to children is another query. If that's the case, you could probably do something like this to be more efficiant.

def self.all_leaves
  Category.find :all, :conditions => "parent_id IS NOT NULL"
end

Your refactoring





Format Copy from initial code

or Cancel