is_categorized is functional
Oleg
committed Aug 22, 2011
commit f970e91e386d9b2e09b9936e88c4351121ca672b
Showing 2
changed files with
62 additions
and 2 deletions
comfortable_mexican_sofa/extensions/is_categorized.rb b/lib/comfortable_mexican_sofa/extensions/is_categorized.rb
+24
-2
| @@ | @@ -6,12 +6,34 @@ module ComfortableMexicanSofa::IsCategorized |
| module ClassMethods | |
| def cms_is_categorized | |
| + | include ComfortableMexicanSofa::IsCategorized::InstanceMethods |
| + | |
| + | has_many :categorizations, |
| + | :as => :categorized, |
| + | :dependent => :destroy |
| has_many :categories, | |
| - | :through => :categorizations, |
| - | :as => :categorized |
| + | :through => :categorizations |
| + | |
| + | attr_accessor :category_ids |
| + | |
| + | after_save :sync_categories |
| end | |
| end | |
| + | module InstanceMethods |
| + | def sync_categories |
| + | (self.category_ids || {}).each do |category_id, flag| |
| + | case flag.to_i |
| + | when 1 |
| + | if category = Cms::Category.find_by_id(category_id) |
| + | category.categorizations.create(:categorized => self) |
| + | end |
| + | when 0 |
| + | self.categorizations.where(:category_id => category_id).destroy_all |
| + | end |
| + | end |
| + | end |
| + | end |
| end | |
| ActiveRecord::Base.send :include, ComfortableMexicanSofa::IsCategorized | |
| \ No newline at end of file | |
test/unit/models/categorization_test.rb
+38
-0
| @@ | @@ -22,4 +22,42 @@ class CmsCategorizationTest < ActiveSupport::TestCase |
| end | |
| end | |
| + | def test_categorized_relationship |
| + | file = cms_files(:default) |
| + | assert file.respond_to?(:category_ids) |
| + | assert_equal 1, file.categories.count |
| + | assert_equal cms_categories(:default), file.categories.first |
| + | |
| + | assert cms_snippets(:default).respond_to?(:category_ids) |
| + | assert_equal 0, cms_snippets(:default).categories.count |
| + | assert cms_pages(:default).respond_to?(:category_ids) |
| + | assert_equal 0, cms_pages(:default).categories.count |
| + | end |
| + | |
| + | def test_categorized_destruction |
| + | file = cms_files(:default) |
| + | assert_difference ['Cms::File.count', 'Cms::Categorization.count'], -1 do |
| + | file.destroy |
| + | end |
| + | end |
| + | |
| + | def test_categorized_syncing |
| + | snippet = cms_snippets(:default) |
| + | assert_equal 0, snippet.categories.count |
| + | |
| + | snippet.update_attribute(:category_ids, { |
| + | cms_categories(:default).id => 1, |
| + | 'invalid' => 1 |
| + | }) |
| + | snippet.reload |
| + | assert_equal 1, snippet.categories.count |
| + | |
| + | snippet.update_attribute(:category_ids, { |
| + | cms_categories(:default).id => 0, |
| + | 'invalid' => 0 |
| + | }) |
| + | snippet.reload |
| + | assert_equal 0, snippet.categories.count |
| + | end |
| + | |
| end | |
| \ No newline at end of file | |