Module: Platanus::TagSetAttr::ClassMethods

Defined in:
lib/platanus/tag_set.rb

Instance Method Summary collapse

Instance Method Details

#attr_tagset(_name, _options = {}) ⇒ Object

Adds a tag list attribute to the model.



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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/platanus/tag_set.rb', line 35

def attr_tagset(_name, _options={})

  _name = _name.to_s

  send :serialize, _name, Platanus::Serializers::TagSet

  klass = class << self; self; end

  klass.send :define_method, "search_by_#{_name.singularize}" do |_opt={}|

    target = self

    # The 'any' filter matches if one of the tokens match
    if _opt.has_key? :any
      params = []; any_sql = []
      Array(_opt[:any]).collect do |token|
        params << "%::#{token}::%"
        any_sql << "#{_name} LIKE ?"
      end
      target = target.where("(#{or_sql.join(' OR ')})", *params) if params.length > 0
    end

    # The 'all' filter matches if all of the tokens match
    if _opt.has_key? :all
      params = []; and_sql = []
      Array(_opt[:all]).each do |token|
        params << "%::#{token}::%"
        and_sql << "#{_name} LIKE ?"
      end
      target = target.where("#{and_sql.join(' AND ')}", *params) if params.length > 0
    end

    # The 'none' filter matches if none of the tokens match
    if _opt.has_key? :none
      params = []; ex_sql = []
      Array(_opt[:none]).each do |token|
        params << "%::#{token}::%"
        ex_sql << "#{_name} is NULL OR #{_name} NOT LIKE ?"
      end
      target = target.where("#{ex_sql.join(' AND ')}", *params) if params.length > 0
    end

    return target
  end
end