Sha256: 21b2ca2aba25e9af44486a459b6f4f2bad1de1c4b3b4ef78c0b60d19e698f467

Contents?: true

Size: 896 Bytes

Versions: 9

Compression:

Stored size: 896 Bytes

Contents

# frozen_string_literal: true

#
# Public: Support taggable entities
#
module TagAble
  extend ActiveSupport::Concern

  included do
    #
    # Fields
    #
    has_many :tags, dependent: :destroy, inverse_of: :model, class_name: 'Tag', foreign_key: :model_id
  end

  # @abstract Update the tags associated with the model
  # First update what is from the updated tags
  # Then delete any that are no longer associated with them
  # @param updated_tags Array<Types::Tag> - tags to update with
  def sync_tags(updated_tags)
    updated_tags.each do |t|
      tag = tags.where(key: t.key).first_or_initialize(key: t.key, model: self)
      tag.update! value: t.value
    end
    keys = updated_tags.map(&:key)
    tags.each { |t| t.destroy unless keys.include?(t.key) }
  end

  def tag_value(key, default = nil)
    tags.find_by(key: key.to_s).value
  rescue StandardError
    default
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
web47core-3.2.20 lib/app/models/concerns/tag_able.rb
web47core-3.2.19 lib/app/models/concerns/tag_able.rb
web47core-3.2.18 lib/app/models/concerns/tag_able.rb
web47core-3.2.17 lib/app/models/concerns/tag_able.rb
web47core-3.2.16 lib/app/models/concerns/tag_able.rb
web47core-3.2.15 lib/app/models/concerns/tag_able.rb
web47core-3.2.14 lib/app/models/concerns/tag_able.rb
web47core-3.2.13 lib/app/models/concerns/tag_able.rb
web47core-3.2.12 lib/app/models/concerns/tag_able.rb