Class: FilterTable::Factory
- Inherits:
-
Object
- Object
- FilterTable::Factory
- Defined in:
- lib/utils/filter.rb
Instance Method Summary collapse
- #add(method_name, opts = {}, &block) ⇒ Object
- #add_accessor(method_name) ⇒ Object
-
#connect(resource, table_accessor) ⇒ Object
rubocop:disable Metrics/AbcSize.
-
#initialize ⇒ Factory
constructor
A new instance of Factory.
Constructor Details
#initialize ⇒ Factory
Returns a new instance of Factory.
135 136 137 138 139 |
# File 'lib/utils/filter.rb', line 135 def initialize @accessors = [] @fields = {} @blocks = {} end |
Instance Method Details
#add(method_name, opts = {}, &block) ⇒ Object
192 193 194 195 196 197 198 199 200 201 |
# File 'lib/utils/filter.rb', line 192 def add(method_name, opts = {}, &block) if method_name.nil? throw RuntimeError, "Called filter.add for resource #{@resource} with method name nil!" end field_name = opts[:field] || method_name @fields[method_name.to_sym] = field_name @blocks[method_name.to_sym] = block self end |
#add_accessor(method_name) ⇒ Object
184 185 186 187 188 189 190 |
# File 'lib/utils/filter.rb', line 184 def add_accessor(method_name) if method_name.nil? throw RuntimeError, "Called filter.add_delegator for resource #{@resource} with method name nil!" end @accessors.push(method_name) self end |
#connect(resource, table_accessor) ⇒ Object
rubocop:disable Metrics/AbcSize
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 |
# File 'lib/utils/filter.rb', line 141 def connect(resource, table_accessor) # rubocop:disable Metrics/AbcSize # create the table structure fields = @fields blocks = @blocks struct_fields = fields.values # the struct to hold single items from the #entries method entry_struct = Struct.new(*struct_fields.map(&:to_sym)) do attr_accessor :__filter def to_s # rubocop:disable Lint/NestedMethodDefinition @__filter || super end end unless struct_fields.empty? # the main filter table table = Class.new(Table) { fields.each do |method, field_name| block = blocks[method] define_method method.to_sym do |condition = Show, &cond_block| return block.call(self, condition) unless block.nil? return where(nil).get_fields(field_name) if condition == Show && !block_given? where({ field_name => condition }, &cond_block) end end define_method :new_entry do |hashmap, filter = ''| return entry_struct.new if hashmap.nil? res = entry_struct.new(*struct_fields.map { |x| hashmap[x] }) res.__filter = filter res end } # define all access methods with the parent resource accessors = @accessors + @fields.keys accessors.each do |method_name| resource.send(:define_method, method_name.to_sym) do |*args, &block| filter = table.new(self, method(table_accessor).call, ' with') filter.method(method_name.to_sym).call(*args, &block) end end end |