demarches-normaliennes/app/models/columns/json_path_column.rb
2024-11-05 09:38:27 +01:00

49 lines
1.1 KiB
Ruby
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# frozen_string_literal: true
class Columns::JSONPathColumn < Columns::ChampColumn
attr_reader :jsonpath
def initialize(procedure_id:, label:, stable_id:, tdc_type:, jsonpath:, displayable:, type: :text)
@jsonpath = quote_string(jsonpath)
super(
procedure_id:,
label:,
stable_id:,
tdc_type:,
displayable:,
type:
)
end
def filtered_ids(dossiers, search_terms)
value = quote_string(search_terms.join('|'))
condition = %{champs.value_json @? '#{jsonpath} ? (@ like_regex "#{value}" flag "i")'}
dossiers.with_type_de_champ(stable_id)
.where(condition)
.ids
end
def options_for_select
case jsonpath.split('.').last
when 'departement_code'
APIGeoService.departements.map { ["#{_1[:code]} #{_1[:name]}", _1[:code]] }
when 'region_name'
APIGeoService.regions.map { [_1[:name], _1[:name]] }
else
[]
end
end
private
def column_id = "type_de_champ/#{stable_id}-#{jsonpath}"
def typed_value(champ)
champ.value_json&.dig(*jsonpath.split('.')[1..])
end
def quote_string(string) = ActiveRecord::Base.connection.quote_string(string)
end