Sha256: 11a6837ef4f8fb29f4543bdbb26afcd565c605ac58ba5f1b650a34a8809297b5

Contents?: true

Size: 1.43 KB

Versions: 1

Compression:

Stored size: 1.43 KB

Contents

class Tag
  inherit Mongo::Model
  collection :tags

  rad.extension :tag_model, self

  FORBIDDEN_CHARACTERS = /<>,/
  TAG_LIST_DELIMITER = ','

  attr_accessor :name, :count
  assign :name, String, true
  validates_presence_of :name, :count
  validate :validate_name

  attr_reader :context
  def context
    if name.to_s =~ /:/
      @context = name.split(/:/).first
    else
      remove_instance_variable :@context if instance_variable_defined? :@context
      nil
    end
  end
  before_save :context

  def update_count!
    new_count = Item.count tags: {_in: [name]}
    unless count == new_count
      self.count = new_count
      self.save!
    end
  end

  class << self
    def valid_name? name
      name.present? and name !~ FORBIDDEN_CHARACTERS
    end

    def create_tags! tags
      tags.each do |name|
        if tag = Tag.by_name(name)
          # TODO3 preformance lost
          tag.update_count!
        else
          tag = Tag.new name: name
          tag.count = 1
          tag.save!
        end
      end
    end

    def update_tags! before, after
      create_tags! after - before
      delete_tags! before - after
    end

    def delete_tags! tags
      tags.each do |name|
        if tag = Tag.by_name(name)
          tag.update_count!
          tag.destroy if tag.count == 0
        end
      end
    end
  end

  protected
    def validate_name
      errors.add :name, t(:invalid_tag_name) unless Tag.valid_name?(name)
    end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rad_kit-0.0.10 app/models/tag.rb