Sha256: b08d644f59c2531b1ac2ae461402900628cfac6fe06c19be180d1186eb20be53

Contents?: true

Size: 1.87 KB

Versions: 2

Compression:

Stored size: 1.87 KB

Contents

module Banyan
  module Categorizable
    def self.included(base)
      base.extend(ClassMethods)
    end

    module ClassMethods
      # Add categories to model
      # @param [Hash] opts Options for connection with categories
      # @option opts [Boolean] :single Should categories be connected via has_one instead of has_many? Default: false
      # @option opts [String] :as Association under which category will handle specified categoriable list. Default: class_name.underscore.gsub('/','___') + '_categorizations'
      def acts_as_categorizable(opts = {})
        single = !!opts.delete(:single)
        as = opts.delete(:as) || (self.name.underscore.gsub('/','___') + '_categorizations')

        if single
          has_one :categorization, :as => :categorizable, :class_name => "::Banyan::Categorization", :dependent => :destroy
          has_one :category, opts.merge(:through => :categorization)
        else
          has_many :categorizations, :as => :categorizable, :class_name => "::Banyan::Categorization", :dependent => :destroy
          has_many :categories, opts.merge(:through => :categorizations, :uniq => true)
        end

        Banyan::Category.has_many as, :through => :categorizations, :source => :categorizable, :source_type => self.name
      end

      # Add category groups to model
      # @param [Hash] opts Options for connection with category groups
      # @option opts [Boolean] :single Should groups be connected via has_one instead of has_many? Default: false
      def acts_as_group_categorizable(opts = {})
        single = !!opts.delete(:single)

        if single
          has_one :category_group, opts.merge(:as => :group_categorizable, :class_name => "Banyan::CategoryGroup")
        else
          has_many :category_groups, opts.merge(:as => :group_categorizable, :class_name => "Banyan::CategoryGroup", :uniq => true)
        end
      end
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
banyan-1.1.1 lib/banyan/categorizable.rb
banyan-1.0.1 lib/banyan/categorizable.rb