johnhamelink
3/12/2014 - 12:50 AM

category.rb

class Category < ActiveRecord::Base
  default_scope { order('name ASC') }

  has_ancestry
  validates  :name, :presence => true

  has_many   :paths
  has_many   :texts
  has_many   :widgets
  has_many   :icons

  def self.arrange_paths_as_array(options={}, hash=nil)
    hash ||= arrange(options)

    arr = []
    hash.each do |node,children|
      if children.empty?
        arr << Path.where(:category_id => node.id).select(:char, :thumb).map {|path| {:char => path.char, :thumb => path.thumb_relative }}
      else
        arr << arrange_paths_as_array(options, children) unless children.empty?
      end
    end

    arr
  end

  def self.arrange_icons_as_array(options={}, hash=nil)
    hash ||= arrange(options)

    arr = []
    cats = IconFile.select(:category_id)
                    .group(:category_id)
                    .map {|i| i.category_id }

    hash.each do |node,children|
      if cats.include? node.id
        arr << IconFile
                .where(:category_id => node.id)
                .select(:char, :path)
                .map{|i| { :char => i.char, :path => i.path_relative } }
      else
        arr << arrange_icons_as_array(options, children) unless children.empty?
      end
    end

    arr
  end
end