class Tally::RecordSearcher

Attributes

params[R]

Public Class Methods

new(params = {}) click to toggle source
# File lib/tally/record_searcher.rb, line 6
def initialize(params = {})
  @params = params || {}

  if ActionController::Parameters === params
    if params.permitted?
      @params = params.to_h
    else
      @params = {}
    end
  end

  @params = @params.symbolize_keys
end

Public Instance Methods

days() click to toggle source
# File lib/tally/record_searcher.rb, line 20
def days
  @keys ||= build_search_scope.select(:day).distinct.reorder(day: :desc)
end
keys() click to toggle source
# File lib/tally/record_searcher.rb, line 24
def keys
  @keys ||= build_search_scope.select(:key).distinct.reorder(:key)
end
records() click to toggle source
# File lib/tally/record_searcher.rb, line 28
def records
  @records ||= build_search_scope
end

Private Instance Methods

build_recordable_from_params() click to toggle source
# File lib/tally/record_searcher.rb, line 38
def build_recordable_from_params
  id = params[:id].to_i
  model = params[:type].to_s.classify.safe_constantize

  if id > 0 && model.respond_to?(:find_by_id)
    model.find_by_id(id)
  end
end
build_search_scope() click to toggle source
# File lib/tally/record_searcher.rb, line 47
def build_search_scope
  scope = Record.all

  if recordable
    scope = scope.where(recordable: recordable)
  elsif params[:type].present?
    scope = scope.where(recordable_type: params[:type])
  end

  if key
    scope = scope.where(key: key)
  end

  if start_date && end_date
    scope = scope.where(day: (start_date..end_date))
  elsif start_date
    scope = scope.where(day: start_date..Float::INFINITY)
  elsif end_date
    scope = scope.where(Record.arel_table[:day].lteq(end_date))
  end

  scope.order(day: :desc)
end
end_date() click to toggle source
# File lib/tally/record_searcher.rb, line 71
def end_date
  if params[:end_date]
    @end_date ||= to_date(:end_date)
  end
end
key() click to toggle source
# File lib/tally/record_searcher.rb, line 77
def key
  if params[:key].present?
    @key ||= params[:key].to_s.gsub(":", ".").downcase.strip
  end
end
recordable() click to toggle source
# File lib/tally/record_searcher.rb, line 83
def recordable
  @recordable ||= if ActiveRecord::Base === params[:record]
    params[:record]
  elsif params[:id] && params[:type]
    build_recordable_from_params
  end
end
start_date() click to toggle source
# File lib/tally/record_searcher.rb, line 91
def start_date
  if params[:start_date]
    @start_date ||= to_date(:start_date)
  end
end
to_date(param_key) click to toggle source
# File lib/tally/record_searcher.rb, line 97
def to_date(param_key)
  value = params[param_key].presence
  return nil unless value.present?
  return value if value.is_a?(Date)
  return value.to_date if value.is_a?(DateTime)
  return value.to_date if value.is_a?(Time)

  Date.parse(value)
rescue
  nil
end