Class: Plutonium::Query::Filters::Date

Inherits:
Plutonium::Query::Filter show all
Defined in:
lib/plutonium/query/filters/date.rb

Overview

Date filter for date/datetime columns

Examples:

Filter by exact date

filter :created_at, with: :date, predicate: :eq

Filter by date before

filter :due_date, with: :date, predicate: :lt

Filter by date on or after

filter :start_date, with: :date, predicate: :gteq

Constant Summary collapse

VALID_PREDICATES =
[
  :eq,    # Equal (on this date)
  :not_eq, # Not equal
  :lt,    # Less than (before)
  :lteq,  # Less than or equal (on or before)
  :gt,    # Greater than (after)
  :gteq   # Greater than or equal (on or after)
].freeze

Instance Attribute Summary

Attributes inherited from Plutonium::Query::Filter

#key

Instance Method Summary collapse

Methods inherited from Plutonium::Query::Filter

lookup

Methods included from Definition::Presentable

#description, #icon, #label

Constructor Details

#initialize(predicate: :eq) ⇒ Date

Returns a new instance of Date.



25
26
27
28
29
30
31
# File 'lib/plutonium/query/filters/date.rb', line 25

def initialize(predicate: :eq, **)
  super(**)
  unless VALID_PREDICATES.include?(predicate)
    raise ArgumentError, "unsupported predicate #{predicate}. Valid predicates are: #{VALID_PREDICATES.join(", ")}"
  end
  @predicate = predicate
end

Instance Method Details

#apply(scope, value:) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/plutonium/query/filters/date.rb', line 33

def apply(scope, value:)
  return scope if value.blank?

  date_value = parse_date(value)
  return scope unless date_value

  case @predicate
  when :eq
    scope.where(key => date_value.all_day)
  when :not_eq
    scope.where.not(key => date_value.all_day)
  when :lt
    scope.where(key => ...date_value.beginning_of_day)
  when :lteq
    scope.where(key => ..date_value.end_of_day)
  when :gt
    scope.where(key => (date_value.end_of_day + 1.second)..)
  when :gteq
    scope.where(key => date_value.beginning_of_day..)
  else
    raise NotImplementedError, "date filter predicate #{@predicate}"
  end
end

#customize_inputsObject



57
58
59
60
# File 'lib/plutonium/query/filters/date.rb', line 57

def customize_inputs
  input :value, as: :date
  field :value, placeholder: generate_placeholder
end