mirror of
https://github.com/inspec/inspec
synced 2024-11-27 07:00:39 +00:00
add general filter utility for resources
This commit is contained in:
parent
8fec08e6d7
commit
d86161c616
1 changed files with 43 additions and 0 deletions
43
lib/utils/filter.rb
Normal file
43
lib/utils/filter.rb
Normal file
|
@ -0,0 +1,43 @@
|
|||
# encoding: utf-8
|
||||
# author: Dominik Richter
|
||||
# author: Christoph Hartmann
|
||||
|
||||
module Inspec
|
||||
module Filter
|
||||
module Show; end
|
||||
|
||||
def add_filter(field_name)
|
||||
fail "Called add_filter in resource #{self} with field name nil!" if field_name.nil?
|
||||
method_name = field_name.to_s
|
||||
# methods will alwas target plurals; this is why the suffix 's' is mandatory
|
||||
method_name += 's' unless method_name.end_with? 's'
|
||||
|
||||
define_method method_name.to_sym do |condition = Show|
|
||||
return get_fields(field_name) if condition == Show
|
||||
where({ field_name => condition })
|
||||
end
|
||||
end
|
||||
|
||||
def self.where(table, conditions = {})
|
||||
return self if !conditions.is_a?(Hash) || conditions.empty?
|
||||
filters = ''
|
||||
conditions.each do |field, condition|
|
||||
filters += " #{field} = #{condition.inspect}"
|
||||
table = filter_lines(table, field, condition)
|
||||
end
|
||||
[table, filters]
|
||||
end
|
||||
|
||||
def self.filter_lines(table, field, condition)
|
||||
table.find_all do |line|
|
||||
next unless line.key?(field)
|
||||
case line[field]
|
||||
when condition
|
||||
true
|
||||
else
|
||||
false
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
Loading…
Reference in a new issue