Skip to content

Instantly share code, notes, and snippets.

@Plotist
Last active May 18, 2021 20:55
Show Gist options
  • Save Plotist/7005ed3fc333a60aa1d220e5dcc8f18d to your computer and use it in GitHub Desktop.
Save Plotist/7005ed3fc333a60aa1d220e5dcc8f18d to your computer and use it in GitHub Desktop.
Ensures that provided timezones are respected while converting UTC/Unrecognized timezones into zone set by Time.zone
module Api::ParamsSanitizer
def sanitize_param_timezones
params.merge!(traverse_params(params.to_unsafe_h))
end
def traverse_params(params)
params.map { |k, v| traverser(k, v) }.to_h
end
def traverser(key, value)
new_val = value
case value.class.name
when "ActionController::Parameters", "Hash", "ActiveSupport::HashWithIndifferentAccess"
new_val = traverse_params(value)
when "Array"
new_val = value.map { |array_val| traverser(key, array_val)[1] }
else
new_val = process_date_parameter(value) if date_parameter_names.include?(key)
end
[key, new_val]
end
# @param value [String] string representation of date or datetime
# @return [DateTime] DateTime with parsed timezone offset of
# DateTime with PDT (Time.zone) offset
# @note Respects any timezone parsed from the string except for UTC
def process_date_parameter(value)
parsed_with_zone = DateTime.parse(value)
if parsed_with_zone.utc_offset.zero?
parsed_with_zone.in_time_zone.to_datetime
else
parsed_with_zone
end
rescue => _e
value
end
def hash_traversable?(param)
%w[ActionController::Parameters, Hash].include? param.class
end
def date_parameter_names
@date_parameter_names ||=
%w[
start_date end_date finish_date from_date to_date publication_date
last_opened_date current_school_year_opening_date loan_start loan_expiration
]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment