add exported_column with its type

Co-authored-by: mfo <mfo@users.noreply.github.com>
This commit is contained in:
Christophe Robillard 2024-10-25 14:19:56 +02:00 committed by mfo
parent e1e497bd7b
commit b2c3887520
No known key found for this signature in database
GPG key ID: 7CE3E1F5B794A8EC
3 changed files with 54 additions and 0 deletions

View file

@ -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

View file

@ -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

View file

@ -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/export_item_type")
require Rails.root.join("app/types/sorted_column_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/filtered_column_type")
require Rails.root.join("app/types/exported_column_type")
ActiveSupport.on_load(:active_record) do ActiveSupport.on_load(:active_record) do
ActiveRecord::Type.register(:column, ColumnType) ActiveRecord::Type.register(:column, ColumnType)
ActiveRecord::Type.register(:export_item, ExportItemType) ActiveRecord::Type.register(:export_item, ExportItemType)
ActiveRecord::Type.register(:sorted_column, SortedColumnType) ActiveRecord::Type.register(:sorted_column, SortedColumnType)
ActiveRecord::Type.register(:filtered_column, FilteredColumnType) ActiveRecord::Type.register(:filtered_column, FilteredColumnType)
ActiveRecord::Type.register(:exported_column, ExportedColumnType)
end end