Module: Mongoid::Tag::ClassMethods

Defined in:
lib/mongoid_tag/tag.rb

Instance Method Summary collapse

Instance Method Details

#tag(*args) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/mongoid_tag/tag.rb', line 14

def tag(*args)
  options = args.extract_options!
  field_name = (args.blank? ? :tags : args.shift).to_sym
  array_field = "#{field_name}_array".to_sym

  #set default options
  options.reverse_merge!({
    :array_field => array_field
  })

  # register / update settings
  class_options = tagify_options || {}
  class_options[field_name] = options
  self.tagify_options = class_options

  #create fields
  field field_name, :type => String, :default => ""
  field array_field, :type => Array, :default => []

  #class methods
  class_eval %(
    class << self
      def with_any_#{field_name}(tags)
        any_in(:#{array_field} => tags.to_a)
      end

      def with_all_#{field_name}(tags)
        all_in(:#{array_field} => tags.to_a)
      end

      def without_#{field_name}(tags)
        not_in(:#{array_field} => tags.to_a)
      end
    end
  )

  #instance methods
  class_eval %(
    def #{field_name}=(s)
      super
      write_attribute(:#{array_field}, convert_string_to_array(s))
    end

    def #{array_field}=(a)
      super
      write_attribute(:#{field_name}, convert_array_to_string(a))
    end
  )

end