diff --git a/app/models/category.rb b/app/models/category.rb index 17c4d68..4f860ce 100644 --- a/app/models/category.rb +++ b/app/models/category.rb @@ -24,9 +24,31 @@ class Category < ActiveRecord::Base def name=(value) self[:name] = value - unless self.name.empty? + unless self.name.blank? self.slug = self.name.transliterate.downcase.gsub( /[^-a-z0-9~\s\.:;+=_]/, '').gsub(/[\s\.:;=_+]+/, '-').gsub(/[\-]{2,}/, '-').to_s end end + def slug=(value) + self[:slug] = value + unless self.slug.blank? + self.path = self.calculate_path + end + end + + # calculates the full path to this category using parent's path. + def calculate_path + if self.top_level? + self.slug + else + self.parent.calculate_path + "/" + self.slug + end + end + + before_create do |cat| + if cat.path == cat.slug && (! cat.top_level?) + cat.path = cat.calculate_path + end + end + end diff --git a/test/unit/category_test.rb b/test/unit/category_test.rb index 40ae55d..1cb9503 100644 --- a/test/unit/category_test.rb +++ b/test/unit/category_test.rb @@ -105,13 +105,25 @@ class CategoryTest < Test::Unit::TestCase def test_path_for_toplevel c = Category.new(:name => 'top_level') - assert_equal 'top_level', c.path + assert_equal 'top-level', c.path end def test_path_for_subcategory c1 = Category.new(:name => 'parent') - c2 = Category.new(:name => 'child') + + c2 = Category.new + c2.parent = c1 + c2.name = 'child' + + assert_equal 'parent/child', c2.path + end + + def test_save_ + c1 = Category.create!(:name => 'parent', :environment_id => @env.id) + + c2 = Category.new(:name => 'child', :environment_id => @env.id) c2.parent = c1 + c2.save! assert_equal 'parent/child', c2.path end -- libgit2 0.21.2