Module: ScopedTags::ActiveRecordAdditions

Defined in:
lib/scoped_tags/active_record_additions.rb

Defined Under Namespace

Modules: ClassMethods, InstanceMethods

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/scoped_tags/active_record_additions.rb', line 5

def self.included(base)
  base.class_eval do
    def self.scoped_tags(contexts, options = nil)
      self.class.instance_eval{ attr_accessor :tag_contexts }

      raise ScopedTagsError, 'context is required for scoped-tags setup' if contexts.blank?

      self.tag_contexts = [contexts].flatten

      has_many :taggings,  :as => :taggable,       :class_name => 'Tagging', :dependent => :delete_all
      has_many :base_tags, :through => :taggings,  :class_name => 'Tag',     :source => :tag,   :readonly => true

      self.tag_contexts.each do |context|
        has_many context, :through => :taggings, :class_name => 'Tag',
                          :source  => :tag,
                          :conditions => { :tags => { :context => context.to_s.downcase } }

        c = context.to_s.singularize
        define_method("#{c}_list")   { get_tag_list(context) }
        define_method("#{c}_list=")  { |new_list| set_tag_list(context, new_list) }
        self.class.instance_eval do
          define_method("tagged_with_#{context}") { |*args| find_tagged_with(args.first, context.to_s, args.extract_options!) }
        end
      end

      self.send :extend,  ClassMethods
      self.send :include, InstanceMethods
    end
  end
end