Sha256: 8e34b685d05ea48391d9a87eea575c099dcc7a66940d2a4d3e3e6864b27af87e

Contents?: true

Size: 1.01 KB

Versions: 6

Compression:

Stored size: 1.01 KB

Contents

module Categorical
  module Concerns
    module Models
      module Tag
        extend ActiveSupport::Concern

        included do
          has_many :taggings

          validates :label, presence: true, uniqueness: { case_sensitive: false }
          validates :label, length: { maximum: 244 }
        end

        def to_s
          label
        end

        # Override #method_missing to allow the class to attempt to find tagged
        # taggables of the given type. 
        #
        # For example when `tag.posts` is called method_missing will attempt to
        # find any taggings of type post and then grab them in an active record
        # query
        def method_missing(name, *args)
          klass_name = name.to_s.singularize.camelcase
          klass = klass_name.constantize

          klass_instance_ids =
            taggings.where(taggable_type: klass_name).map(&:taggable_id)

          klass.where(id: klass_instance_ids)

          rescue NameError
            super
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
categorical-0.0.9.1 lib/categorical/concerns/models/tag.rb
categorical-0.0.9 lib/categorical/concerns/models/tag.rb
categorical-0.0.9.rc lib/categorical/concerns/models/tag.rb
categorical-0.0.8.rc lib/categorical/concerns/models/tag.rb
categorical-0.0.6.rc lib/categorical/concerns/models/tag.rb
categorical-0.0.4 lib/categorical/concerns/models/tag.rb