Sha256: 6bffcc4aaf125d5ddcf5854c1c1958ab519e0043af08a4de5141a209a10411a4

Contents?: true

Size: 1.53 KB

Versions: 1

Compression:

Stored size: 1.53 KB

Contents

module Tagliani
  module Concerns
    module Taggable
      class Tags < Array
        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

        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.class.to_s,
              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

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

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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tagliani-0.1.0 lib/tagliani/concerns/taggable/tags.rb