Sha256: a6e11dfd776feaf5eb4443e22f19efa53ac98c2dd9c8abacc889e161ee3f44e6

Contents?: true

Size: 1.71 KB

Versions: 21

Compression:

Stored size: 1.71 KB

Contents

# frozen_string_literal: true

class Tag < ApplicationRecord
  include PagesCore::HumanizableParam
  has_many :taggings, dependent: :destroy

  scope :by_name, -> { order("name ASC") }
  scope :pinned, -> { where(pinned: true) }
  scope :sorted, -> { order("pinned DESC, name ASC") }

  class << self
    def tags_and_suggestions_for(taggable, options = {})
      limit = options[:limit] || 100
      tags = (taggable.tags.sorted + pinned.sorted).uniq

      return tags unless tags.count < limit

      tags + suggestions(taggable, tags, limit)[0...(limit - tags.length)]
    end

    def parse(*tags)
      Array(tags).flatten
                 .map { |tag| tag.is_a?(Tag) ? tag.name : tag }
                 .map { |tag| tag.split(",") }
                 .flatten
                 .map(&:strip)
    end

    private

    def suggestions(taggable, tags, limit)
      suggestions = taggable_suggestions(taggable, limit).to_a
      suggestions += all_suggestions(limit) if suggestions.length < limit
      suggestions.reject { |t| tags.include?(t) }.uniq[0...limit]
    end

    def taggable_suggestions(taggable, limit)
      all_suggestions(limit)
        .where(taggings: { taggable_type: taggable.class.to_s })
    end

    def all_suggestions(limit)
      Tag.joins(:taggings)
         .select("tags.*, COUNT(tags.id) AS counter")
         .group("tags.id")
         .order("counter DESC")
         .limit(limit)
    end

    def default_options
      { limit: 100 }
    end
  end

  def tagged
    @tagged ||= taggings.collect(&:taggable)
  end

  def on(taggable)
    taggings.create(taggable: taggable)
  end

  def ==(other)
    super || name == other.to_s
  end

  def to_param
    humanized_param(name)
  end

  def to_s
    name
  end
end

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
pages_core-3.12.7 app/models/tag.rb
pages_core-3.12.6 app/models/tag.rb
pages_core-3.12.5 app/models/tag.rb
pages_core-3.12.4 app/models/tag.rb
pages_core-3.12.3 app/models/tag.rb
pages_core-3.12.2 app/models/tag.rb
pages_core-3.12.1 app/models/tag.rb
pages_core-3.12.0 app/models/tag.rb
pages_core-3.11.3 app/models/tag.rb
pages_core-3.11.2 app/models/tag.rb
pages_core-3.11.1 app/models/tag.rb
pages_core-3.11.0 app/models/tag.rb
pages_core-3.10.2 app/models/tag.rb
pages_core-3.10.1 app/models/tag.rb
pages_core-3.9.2 app/models/tag.rb
pages_core-3.9.1 app/models/tag.rb
pages_core-3.9.0 app/models/tag.rb
pages_core-3.8.3 app/models/tag.rb
pages_core-3.8.2 app/models/tag.rb
pages_core-3.8.1 app/models/tag.rb