Class: EasyTags::TaggableContextMethods

Inherits:
Object
  • Object
show all
Defined in:
lib/easy_tags/taggable_context_methods.rb

Overview

Handles injecting of the dynamic context related methods Example:

easy_tags_on :bees

# will create:

has_many :bees_taggings
has_many :bees_tags

def bees
def bees=
def bees_list
def bees_list=

Class Method Summary collapse

Class Method Details

.inject(class_instance:, context:) ⇒ Object

rubocop:disable Metrics/MethodLength



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/easy_tags/taggable_context_methods.rb', line 20

def inject(class_instance:, context:)
  class_instance.class_eval <<-RUBY, __FILE__, __LINE__ + 1 # rubocop:disable Style/DocumentDynamicEvalDefinition
    has_many(
      :#{context}_taggings, -> { includes(:tag).where(context: :#{context}) },
      as: :taggable,
      class_name: 'EasyTags::Tagging',
      dependent: :destroy
    )

    has_many(
      :#{context}_tags,
      class_name: 'EasyTags::Tag',
      through: :#{context}_taggings,
      source: :tag
    )

    attribute :#{context}_list, ActiveModel::Type::Value.new

    def #{context}
      _taggable_context(:#{context})
    end

    def #{context}=(value)
      _taggable_context(:#{context}).update(value)
      #{context}
    end

    def #{context}_list
      _taggable_context(:#{context}).tags.to_s
    end

    def #{context}_list=(value)
      _taggable_context(:#{context}).update(value)
      #{context}_list
    end

    def #{context}_list_persisted
      _taggable_context(:#{context}).persisted_tags.to_s
    end
  RUBY
end