From b2c3887520d60527c70684ce75c032e9c51017f5 Mon Sep 17 00:00:00 2001 From: Christophe Robillard Date: Fri, 25 Oct 2024 14:19:56 +0200 Subject: [PATCH] add exported_column with its type Co-authored-by: mfo --- app/models/exported_column.rb | 12 ++++++++++ app/types/exported_column_type.rb | 40 +++++++++++++++++++++++++++++++ config/initializers/types.rb | 2 ++ 3 files changed, 54 insertions(+) create mode 100644 app/models/exported_column.rb create mode 100644 app/types/exported_column_type.rb diff --git a/app/models/exported_column.rb b/app/models/exported_column.rb new file mode 100644 index 000000000..5f754c98f --- /dev/null +++ b/app/models/exported_column.rb @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +class ExportedColumn + attr_reader :column, :libelle + + def initialize(column:, libelle:) + @column = column + @libelle = libelle + end + + def id = { id: column.id, libelle: }.to_json +end diff --git a/app/types/exported_column_type.rb b/app/types/exported_column_type.rb new file mode 100644 index 000000000..dddd35532 --- /dev/null +++ b/app/types/exported_column_type.rb @@ -0,0 +1,40 @@ +# frozen_string_literal: true + +class ExportedColumnType < ActiveRecord::Type::Value + # form_input or setter -> type + def cast(value) + value = value.deep_symbolize_keys if value.respond_to?(:deep_symbolize_keys) + + case value + in ExportedColumn + value + in NilClass # default value + nil + # from db + in { id: String|Hash, libelle: String } => h + ExportedColumn.new(column: ColumnType.new.cast(h[:id]), libelle: h[:libelle]) + # from form + in String + h = JSON.parse(value).deep_symbolize_keys + ExportedColumn.new(column: ColumnType.new.cast(h[:id]), libelle: h[:libelle]) + end + end + + # db -> ruby + def deserialize(value) = cast(value&.then { JSON.parse(_1) }) + + # ruby -> db + def serialize(value) + case value + in NilClass + nil + in ExportedColumn + JSON.generate({ + id: value.column.h_id, + libelle: value.libelle + }) + else + raise ArgumentError, "Invalid value for ExportedColumn serialization: #{value}" + end + end +end diff --git a/config/initializers/types.rb b/config/initializers/types.rb index 46f40f05d..ecdf990d7 100644 --- a/config/initializers/types.rb +++ b/config/initializers/types.rb @@ -4,10 +4,12 @@ require Rails.root.join("app/types/column_type") require Rails.root.join("app/types/export_item_type") require Rails.root.join("app/types/sorted_column_type") require Rails.root.join("app/types/filtered_column_type") +require Rails.root.join("app/types/exported_column_type") ActiveSupport.on_load(:active_record) do ActiveRecord::Type.register(:column, ColumnType) ActiveRecord::Type.register(:export_item, ExportItemType) ActiveRecord::Type.register(:sorted_column, SortedColumnType) ActiveRecord::Type.register(:filtered_column, FilteredColumnType) + ActiveRecord::Type.register(:exported_column, ExportedColumnType) end