add exported_column with its type
Co-authored-by: mfo <mfo@users.noreply.github.com>
This commit is contained in:
parent
e1e497bd7b
commit
b2c3887520
3 changed files with 54 additions and 0 deletions
12
app/models/exported_column.rb
Normal file
12
app/models/exported_column.rb
Normal 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
|
40
app/types/exported_column_type.rb
Normal file
40
app/types/exported_column_type.rb
Normal 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
|
|
@ -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
|
||||
|
|
Loading…
Reference in a new issue