demarches-normaliennes/app/models/champs/datetime_champ.rb

62 lines
2 KiB
Ruby
Raw Normal View History

2020-08-06 16:35:45 +02:00
# == Schema Information
#
# Table name: champs
#
# id :integer not null, primary key
# data :jsonb
# fetch_external_data_exceptions :string is an Array
2022-12-01 12:00:21 +01:00
# prefilled :boolean default(FALSE)
# private :boolean default(FALSE), not null
# rebased_at :datetime
# row :integer
# type :string
# value :string
2021-10-05 15:37:13 +02:00
# value_json :jsonb
# created_at :datetime
# updated_at :datetime
# dossier_id :integer
# etablissement_id :integer
# external_id :string
# parent_id :bigint
# row_id :string
# type_de_champ_id :integer
2020-08-06 16:35:45 +02:00
#
2018-02-13 18:18:20 +01:00
class Champs::DatetimeChamp < Champ
before_save :format_before_save
def search_terms
# Text search is pretty useless for datetimes so were not including these champs
end
def to_s
value.present? ? I18n.l(Time.zone.parse(value)) : ""
end
def for_tag
value.present? ? I18n.l(Time.zone.parse(value)) : ""
end
def html_label?
false
end
private
def format_before_save
if (value =~ /=>/).present?
self.value =
begin
hash_date = YAML.safe_load(value.gsub('=>', ': '))
2018-12-24 17:37:57 +01:00
year, month, day, hour, minute = hash_date.values_at(1, 2, 3, 4, 5)
2018-10-25 15:19:29 +02:00
Time.zone.local(year, month, day, hour, minute).strftime("%d/%m/%Y %H:%M")
rescue
nil
end
elsif /^\d{2}\/\d{2}\/\d{4}\s\d{2}:\d{2}$/.match?(value) # old browsers can send with dd/mm/yyyy hh:mm format
self.value = Time.zone.strptime(value, "%d/%m/%Y %H:%M").strftime("%Y-%m-%d %H:%M")
elsif !(/^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}$/.match?(value)) # a datetime not correctly formatted should not be stored
self.value = nil
end
end
2018-02-13 18:18:20 +01:00
end