Class: ActiveFilter::Base
- Inherits:
-
Object
- Object
- ActiveFilter::Base
- Defined in:
- lib/active_filter/base.rb
Instance Attribute Summary collapse
-
#fields ⇒ Object
readonly
Returns the value of attribute fields.
Instance Method Summary collapse
- #each(&block) ⇒ Object
-
#initialize(data, scope = nil) ⇒ Base
constructor
A new instance of Base.
- #model ⇒ Object
- #to_scope ⇒ Object
Constructor Details
#initialize(data, scope = nil) ⇒ Base
Returns a new instance of Base.
8 9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/active_filter/base.rb', line 8 def initialize(data, scope=nil) @data = data @scope = scope @fields = [] self.class._model.columns.each do |column| if self.class._field_names.include?(column.name) || self.class._field_names.include?(column.name.to_sym) @fields << _create_field_from_column(column) end end end |
Instance Attribute Details
#fields ⇒ Object (readonly)
Returns the value of attribute fields.
6 7 8 |
# File 'lib/active_filter/base.rb', line 6 def fields @fields end |
Instance Method Details
#each(&block) ⇒ Object
93 94 95 96 97 98 99 100 101 102 103 |
# File 'lib/active_filter/base.rb', line 93 def each(&block) scope = self.to_scope unless block_given? return scope.each end scope.each do |obj| block.call(obj) end self end |
#model ⇒ Object
89 90 91 |
# File 'lib/active_filter/base.rb', line 89 def model self.class._model end |
#to_scope ⇒ Object
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 |
# File 'lib/active_filter/base.rb', line 105 def to_scope scope = _scoped matched = false @fields.each do |field| # フィールド名でフィルタする name = field.name if @data.include?(name) converted_value = field.convert_value(@data[name]) scope = field.filter(scope, converted_value, "exact") matched = true elsif @data.include?(name.to_sym) converted_value = field.convert_value(@data[name.to_sym]) scope = field.filter(scope, converted_value, "exact") matched = true end # lookup_type でフィルタする lookup_types = [field.lookup_type].flatten lookup_types.each do |lookup_type| lookup = "#{name}__#{lookup_type}" if @data.include?(lookup) converted_value = field.convert_value(@data[lookup]) scope = field.filter(scope, converted_value, lookup_type) matched = true elsif @data.include?(lookup.to_sym) converted_value = field.convert_value(@data[lookup.to_sym]) scope = field.filter(scope, converted_value, lookup_type) matched = true end end end # ユーザーの入力がフィルタにかからなかった場合は # 該当無しにする unless matched scope = scope.where("1 = 2") end scope end |