Module: Mongoid::MinimalTags::ClassMethods

Defined in:
lib/mongoid/minimal_tags/minimal_tags.rb

Instance Method Summary collapse

Instance Method Details

#tag_field(field_name, formatter: MinimalTags.default_formatter) ⇒ Object

Creates a tag field, index, query methods and a callback for tag normalization on save.

Examples:

class Document
  include Mongoid::Document
  include Mongoid::MinimalTags

  tag_field :tags
end

doc = Document.create(tags: ['hello world', 'this is a test']).tags
# => ['hello-world', 'this-is-a-test']

doc == Document.any_tags(['HELLO WORLD']).first
# => true

30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/mongoid/minimal_tags/minimal_tags.rb', line 30

def tag_field(field_name, formatter: MinimalTags.default_formatter)
  field field_name, type: Array, default: []
  index field_name => 1

  # Create the scopes for querying tags
  MinimalTags.query_types.each do |type, prefix|
    scope "#{prefix}_#{field_name}", lambda { |tags|
      criteria.send(type, field_name => formatter.normalize(tags))
    }
  end

  # Normalize tags on save
  set_callback(:save, :before) do
    tags = read_attribute(field_name)
    write_attribute(field_name, formatter.normalize(tags))
  end
end