Class: CafeCar::FilterBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/cafe_car/filter_builder.rb

Instance Method Summary collapse

Constructor Details

#initialize(objects, params) ⇒ FilterBuilder

Returns a new instance of FilterBuilder.



5
6
7
8
# File 'lib/cafe_car/filter_builder.rb', line 5

def initialize(objects, params)
  @objects = objects
  @params  = params
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name) ⇒ Object

Rails' select/check_box read the current value off the object by the field name (object.status); a nested control's name is a dot-path (client.status), so split it to dig the nested param — the same segment walk as #value.



20
21
22
# File 'lib/cafe_car/filter_builder.rb', line 20

def method_missing(name, *, &)
  @params.dig("", *name.to_s.split("."))
end

Instance Method Details

#errorsObject



14
# File 'lib/cafe_car/filter_builder.rb', line 14

def errors     = Hash.new([])

#modelObject



10
# File 'lib/cafe_car/filter_builder.rb', line 10

def model      = @objects.klass

#persisted?Boolean

Returns:

  • (Boolean)


13
# File 'lib/cafe_car/filter_builder.rb', line 13

def persisted? = false

#to_keyObject



11
# File 'lib/cafe_car/filter_builder.rb', line 11

def to_key     = [ model_name.param_key, :filters ]

#to_modelObject



12
# File 'lib/cafe_car/filter_builder.rb', line 12

def to_model   = self

#value(*keys) ⇒ Object

Current value of a (possibly nested) filter param — value(:price, :min) reads ?price.min=, and value("client.owner_id") digs the nested ?client.owner_id= a nested control posts (a dotted key splits into its segments). Nil-safe against shapes a control can't express (a hand-typed ?price=10..20 parses to a Range, not a Hash).



29
30
31
# File 'lib/cafe_car/filter_builder.rb', line 29

def value(*keys)
  keys.flat_map { _1.to_s.split(".") }.reduce(@params[""]) { |v, key| v[key] if v.is_a?(Hash) }
end