Module: LeanTag::Taggable

Defined in:
lib/lean_tag/taggable.rb

Defined Under Namespace

Modules: ClassMethods, InstanceMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/lean_tag/taggable.rb', line 3

def self.extended(base)
  def taggable_on(relation="tags")
    extend ClassMethods

    self.class_exec(relation) do |tag_relation|
      include InstanceMethods

      has_many "#{tag_relation}_taggings".to_sym, -> { where(filter: tag_relation) }, class_name: "LeanTag::Tagging", as: :record, inverse_of: :record, dependent: :destroy
      has_many tag_relation.to_sym, through: "#{tag_relation}_taggings".to_sym, source: :tag

      accepts_nested_attributes_for "#{tag_relation}_taggings", allow_destroy: true

      scope "with_#{tag_relation}", -> { includes(tag_relation) }

      define_method "add_#{tag_relation.to_s.singularize}", ->(tag) { _add_tag(tag, tag_relation) }
      define_method "add_#{tag_relation.to_s.singularize}!", ->(tag) { _add_tag!(tag, tag_relation) }
      define_method "#{tag_relation.to_s.singularize}_list", ->() { _get_tag_list(tag_relation) }
      define_method "remove_#{tag_relation.to_s.singularize}", ->(tag) { _remove_tag(tag, tag_relation) }
      define_method "remove_#{tag_relation.to_s.singularize}!", ->(tag) { _remove_tag!(tag, tag_relation) }
      define_method "#{tag_relation.to_s.singularize}_list=", ->(list) { _set_tag_list(list, tag_relation) }
    end
  end
end

Instance Method Details

#taggable_on(relation = "tags") ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/lean_tag/taggable.rb', line 4

def taggable_on(relation="tags")
  extend ClassMethods

  self.class_exec(relation) do |tag_relation|
    include InstanceMethods

    has_many "#{tag_relation}_taggings".to_sym, -> { where(filter: tag_relation) }, class_name: "LeanTag::Tagging", as: :record, inverse_of: :record, dependent: :destroy
    has_many tag_relation.to_sym, through: "#{tag_relation}_taggings".to_sym, source: :tag

    accepts_nested_attributes_for "#{tag_relation}_taggings", allow_destroy: true

    scope "with_#{tag_relation}", -> { includes(tag_relation) }

    define_method "add_#{tag_relation.to_s.singularize}", ->(tag) { _add_tag(tag, tag_relation) }
    define_method "add_#{tag_relation.to_s.singularize}!", ->(tag) { _add_tag!(tag, tag_relation) }
    define_method "#{tag_relation.to_s.singularize}_list", ->() { _get_tag_list(tag_relation) }
    define_method "remove_#{tag_relation.to_s.singularize}", ->(tag) { _remove_tag(tag, tag_relation) }
    define_method "remove_#{tag_relation.to_s.singularize}!", ->(tag) { _remove_tag!(tag, tag_relation) }
    define_method "#{tag_relation.to_s.singularize}_list=", ->(list) { _set_tag_list(list, tag_relation) }
  end
end