Class: TreeFilter::Slice

Inherits:
Struct
  • Object
show all
Defined in:
lib/tree_filter.rb

Instance Method Summary collapse

Constructor Details

#initialize(attrs = {}) ⇒ Slice

Returns a new instance of Slice.



95
96
97
98
# File 'lib/tree_filter.rb', line 95

def initialize(attrs = {})
  super
  @attrs = attrs
end

Instance Method Details

#filter(value) ⇒ Object



100
101
102
103
104
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
# File 'lib/tree_filter.rb', line 100

def filter(value)
  # With activesupport this will always be evaluated, because `as_json` is
  # monkey-patched on to Object.
  value = value.as_json if value.respond_to?(:as_json)

  case value
  when Hash
    slices = @attrs.dup

    if @attrs.keys.include?('*')
      slices.delete("*")
      extra = value.keys - slices.keys - ['*']
      extra.each do |k|
        slices[k] = nil
      end
    end

    slices.each_with_object({}) do |(attr, slice), ret|
      slice ||= NullSlice.new

      ret[attr] = slice.filter(value[attr])
    end
  when Array
    value.map {|x| filter(x) }
  when Defer
    filter(value.call)
  when Leaf
    filter(value.right)
  else
    value
  end
end