Sha256: 8444cd4a3ba31d0783098ec010e1baf83a43324aedef0ea9879bef939d5ba8b6

Contents?: true

Size: 1.28 KB

Versions: 2

Compression:

Stored size: 1.28 KB

Contents

class Tag < ActiveRecord::Base

  attr_accessible :name

  ### ASSOCIATIONS:

  has_many :taggings, :dependent => :destroy

  ### VALIDATIONS:

  validates_presence_of :name
  validates_uniqueness_of :name

  ### SCOPES:

  def self.named(name)
    where(["name LIKE ?", name])
  end
  
  def self.named_any(list)
    where(list.map { |tag| sanitize_sql(["name LIKE ?", tag.to_s]) }.join(" OR "))
  end
  
  def self.named_like(name)
    where(["name LIKE ?", "%#{name}%"])
  end

  def self.named_like_any(list)
    where(list.map { |tag| sanitize_sql(["name LIKE ?", "%#{tag.to_s}%"]) }.join(" OR "))
  end

  ### CLASS METHODS:

  def self.find_or_create_with_like_by_name(name)
    named_like(name).first || create(:name => name)
  end

  def self.find_or_create_all_with_like_by_name(*list)
    list = [list].flatten

    return [] if list.empty?

    existing_tags = Tag.named_any(list).all
    new_tag_names = list.reject { |name| existing_tags.any? { |tag| tag.name.downcase == name.downcase } }
    created_tags  = new_tag_names.map { |name| Tag.create(:name => name) }

    existing_tags + created_tags
  end

  ### INSTANCE METHODS:

  def ==(object)
    super || (object.is_a?(Tag) && name == object.name)
  end

  def to_s
    name
  end

  def count
    read_attribute(:count).to_i
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
acts-as-taggable-on-2.0.0.pre4 lib/acts_as_taggable_on/tag.rb
acts-as-taggable-on-2.0.0.pre3 lib/acts_as_taggable_on/tag.rb