Module: ConcernsOnRails::Models::Taggable
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/concerns_on_rails/models/taggable.rb
Overview
Lightweight, dependency-free tagging over a single string column. Tags are stored delimiter-joined in one column — no join tables, no tagging engine — so it works on any database, including SQLite.
class Article < ApplicationRecord
include ConcernsOnRails::Taggable
taggable_by :tags # default column :tags
# taggable_by :skills, downcase: true # custom column, case-folded
end
a = Article.new
a.tag_list = "Ruby, Rails, Ruby" # accepts a String or an Array
a.tag_list # => ["Ruby", "Rails"] (stripped + de-duped)
a.("api"); a.("Rails")
a.tagged_with?("ruby") # membership predicate
a.save!
Article.tagged_with("ruby", "rails") # records carrying BOTH tags
Article.tagged_with("ruby", "go", any: true) # records carrying ANY tag
Article. # sorted unique tags in use
Notes:
* Matching is boundary-safe ("rail" does not match "rails").
* A tag must not contain the delimiter (default ",").
* Reach for acts-as-taggable-on when you need tag contexts, ownership,
tag counts/clouds, or polymorphic tags shared across models.
Defined Under Namespace
Modules: ClassMethods
Constant Summary collapse
- LABEL =
"ConcernsOnRails::Models::Taggable".freeze
- DEFAULT_FIELD =
:tags- DEFAULT_DELIMITER =
",".freeze
Instance Method Summary collapse
- #add_tags(*names) ⇒ Object (also: #add_tag)
- #remove_tags(*names) ⇒ Object (also: #remove_tag)
-
#tag_list ⇒ Object
—- instance methods —-.
- #tag_list=(value) ⇒ Object
- #tagged_with?(tag) ⇒ Boolean (also: #has_tag?)
Instance Method Details
#add_tags(*names) ⇒ Object Also known as: add_tag
123 124 125 126 |
# File 'lib/concerns_on_rails/models/taggable.rb', line 123 def (*names) self.tag_list = tag_list + names.flatten.map { |t| self.class.taggable_clean(t) } tag_list end |
#remove_tags(*names) ⇒ Object Also known as: remove_tag
129 130 131 132 133 |
# File 'lib/concerns_on_rails/models/taggable.rb', line 129 def (*names) drop = names.flatten.map { |t| self.class.taggable_clean(t) } self.tag_list = tag_list.reject { |t| drop.include?(t) } tag_list end |
#tag_list ⇒ Object
—- instance methods —-
114 115 116 |
# File 'lib/concerns_on_rails/models/taggable.rb', line 114 def tag_list self.class.taggable_split(self[self.class.taggable_field]) end |
#tag_list=(value) ⇒ Object
118 119 120 121 |
# File 'lib/concerns_on_rails/models/taggable.rb', line 118 def tag_list=(value) = taggable_coerce(value) self[self.class.taggable_field] = .empty? ? nil : .join(self.class.taggable_delimiter) end |
#tagged_with?(tag) ⇒ Boolean Also known as: has_tag?
136 137 138 |
# File 'lib/concerns_on_rails/models/taggable.rb', line 136 def tagged_with?(tag) tag_list.include?(self.class.taggable_clean(tag)) end |