Class: Tagliani::Concerns::Taggable::Tags

Inherits:
Array
  • Object
show all
Defined in:
lib/tagliani/concerns/taggable/tags.rb

Instance Method Summary collapse

Constructor Details

#initialize(parent = nil) ⇒ Tags

Returns a new instance of Tags.



5
6
7
8
9
10
11
12
# File 'lib/tagliani/concerns/taggable/tags.rb', line 5

def initialize(parent = nil)
  @parent = parent
  @index = Tagliani::Search::Index.new
  @tag_kls = @parent.class._tag_kls.constantize
  @async = @parent.class._async
  
  super(search)
end

Instance Method Details

#add(*objects) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/tagliani/concerns/taggable/tags.rb', line 14

def add(*objects)
  objects.flat_map do |hash|
    options = hash.slice(:name)

    begin
      record = @tag_kls.find_or_initialize_by(options)
      record.save
    rescue ActiveRecord::RecordNotUnique
      record = @tag_kls.find_by(options)
    end

    @index.add!({
      object_kls: parent_kls,
      object_id: @parent.id,
      created_at: @parent.try(:created_at),
      tag_id: record.id,
      tag_kls: record.class.to_s,
      tag_type: record.sticker,
      tag_name: record.name,
      last_updated: Time.now
    }, async: @async)
  end
end

#inheritObject



53
54
55
56
57
58
59
60
61
# File 'lib/tagliani/concerns/taggable/tags.rb', line 53

def inherit
  root.each do |object|
    next if object.nil?
    
    self.class.new(object).each do |ref|
      add(name: ref.name)
    end
  end
end

#rootObject



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/tagliani/concerns/taggable/tags.rb', line 63

def root
  klasses = []
  
  if @parent._inherit.respond_to?(:each)
    klasses = @parent._inherit
  else
    klasses << @parent._inherit
  end
  
  objects = klasses.flat_map do |method|
    next if method.nil?
    @parent.send(method)
  end
  
  objects.compact
end

#search(body: {}, where: nil) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/tagliani/concerns/taggable/tags.rb', line 38

def search(body: {}, where: nil)
  body.deep_merge!({
    query: {
      bool: {
        must: [
          { match: { object_kls: parent_kls } },
          { term: { object_id: @parent.id } }
        ]
      }
    }
  })

  Tagliani::Search.new(body: body, where: where).serialize(type: 'tag')
end