Class: NTEE::Category

Inherits:
Object
  • Object
show all
Defined in:
lib/ntee.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCategory

Returns a new instance of Category.



7
8
9
# File 'lib/ntee.rb', line 7

def initialize
  self.subcategories ||= {}
end

Instance Attribute Details

#codeObject

Returns the value of attribute code.



5
6
7
# File 'lib/ntee.rb', line 5

def code
  @code
end

#nameObject

Returns the value of attribute name.



5
6
7
# File 'lib/ntee.rb', line 5

def name
  @name
end

#parentObject

Returns the value of attribute parent.



5
6
7
# File 'lib/ntee.rb', line 5

def parent
  @parent
end

#subcategoriesObject

Returns the value of attribute subcategories.



5
6
7
# File 'lib/ntee.rb', line 5

def subcategories
  @subcategories
end

Instance Method Details

#[](subcategory_code) ⇒ Object



19
20
21
# File 'lib/ntee.rb', line 19

def [](subcategory_code)
  self.subcategories[subcategory_code.to_s]
end

#add_subcategory!(subcategory) ⇒ Object



43
44
45
46
47
# File 'lib/ntee.rb', line 43

def add_subcategory!(subcategory)
  subcategories[subcategory.code.to_s] = subcategory
  subcategory.parent = self
  subcategories
end

#ancestorsObject



31
32
33
34
35
36
37
# File 'lib/ntee.rb', line 31

def ancestors
  if parent
    [parent] + parent.ancestors
  else
    []
  end
end

#as_json(options = {}) ⇒ Object



49
50
51
52
53
54
55
56
57
58
# File 'lib/ntee.rb', line 49

def as_json(options={})
  hsh = {
    'code' => code,
    'name' => name
  }

  hsh['subcategories'] = subcategories.values.as_json(options) if subcategories && subcategories.count > 0

  hsh
end

#attributes=(attributes) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/ntee.rb', line 60

def attributes=(attributes)
  attributes.each do |name, value|
    case name.to_s
    when "code"
      self.code = value
    when "name"
      self.name = value
    when "parent"
      self.parent = value
    when "subcategories"
      subcats = value.collect do |subcat|
        case subcat
        when Category
          subcat
        when Hash
          Category.new.tap { |cat| cat.attributes = subcat }
        else
          raise "Subcategory #{value.inspect} is neither a Category nor a Hash"
        end
      end

      subcats.each do |subcat|
        add_subcategory!(subcat)
      end
    end
  end
end

#descendantsObject



39
40
41
# File 'lib/ntee.rb', line 39

def descendants
  (subcategories.values + subcategories.values.map(&:descendants)).flatten
end

#inspectObject



15
16
17
# File 'lib/ntee.rb', line 15

def inspect
  "<NTEE Category #{code} (#{name})>"
end

#to_sObject



11
12
13
# File 'lib/ntee.rb', line 11

def to_s
  "#{name} (#{code})"
end