Module: Mongoid::TagsArentHard::ClassMethods

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

Instance Method Summary collapse

Instance Method Details

#taggable_with(name, options = {}) ⇒ Object



10
11
12
13
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
# File 'lib/mongoid/tags_arent_hard/tags_arent_hard.rb', line 10

def taggable_with(name, options = {})
  options = {separator: Mongoid::TagsArentHard.config.separator, _name: name}.merge(options)
  self.field(name, type: Mongoid::TagsArentHard::Tags, default: Mongoid::TagsArentHard::Tags.new([], options))
  self.class_eval do
    define_method(name) do
      val = super()
      unless val.is_a?(Mongoid::TagsArentHard::Tags)
        options.merge!(owner: self)
        val = Mongoid::TagsArentHard::Tags.new(val, options)
        self.send("#{name}=", val)
      end
      return val
    end
    define_method("#{name}=") do |val|
      unless val.is_a?(Mongoid::TagsArentHard::Tags)
        options.merge!(owner: self)
        val = Mongoid::TagsArentHard::Tags.new(val, options)
      end
      super(val)
    end

  end
  self.class.send(:define_method, "with_#{name}") do |*val|
    self.send("with_any_#{name}", *val)
  end

  self.class.send(:define_method, "all_#{name}") do
    queryable.distinct(name.to_s)
  end


  self.class.send(:define_method, "with_any_#{name}") do |*val|
    any_in(name => Mongoid::TagsArentHard::Tags.new(*val, {}).tag_list)
  end

  self.class.send(:define_method, "with_all_#{name}") do |*val|
    all_in(name => Mongoid::TagsArentHard::Tags.new(*val, {}).tag_list)
  end

  self.class.send(:define_method, "without_any_#{name}") do |*val|
    not_in(name => Mongoid::TagsArentHard::Tags.new(*val, {}).tag_list)
  end
end