Skip to content

Commit 4f9a486

Browse files
committed
Refactor extract_tree_view_value to avoid exception-based control flow
1 parent d933974 commit 4f9a486

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

app/controllers/inplace_edit_fields_controller.rb

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -165,25 +165,28 @@ def transform_custom_field_values_params
165165
cf_values = params.dig(model_key, :custom_field_values)
166166
raw_value = cf_values.is_a?(Array) ? cf_values : cf_values&.dig(custom_field_id)
167167

168-
{ @attribute => process_cf_raw_value(raw_value) }
168+
{ @attribute => process_cf_raw_value(raw_value, custom_field_id) }
169169
end
170170

171-
def process_cf_raw_value(raw_value)
171+
def process_cf_raw_value(raw_value, custom_field_id)
172172
return raw_value unless raw_value.is_a?(Array)
173173

174-
# Remove empty strings from the hidden field, then extract the actual value.
174+
cleaned_values = raw_value.compact_blank
175175
# FilterableTreeView encodes each selected item as a JSON payload
176176
# {"path":[...],"value":"<id>"} — extract only the "value" field.
177-
cleaned_values = raw_value.compact_blank.filter_map { |v| extract_tree_view_value(v) }
177+
# Only hierarchy-format fields use this encoding, so we check the field format first.
178+
values = if hierarchy_format_custom_field?(custom_field_id)
179+
cleaned_values.map { |v| JSON.parse(v)["value"] }
180+
else
181+
cleaned_values
182+
end
178183
# For single-select, unwrap the array to get the single value
179-
cleaned_values.size <= 1 ? cleaned_values.first : cleaned_values
184+
values.size <= 1 ? values.first : values
180185
end
181186

182-
def extract_tree_view_value(raw)
183-
parsed = JSON.parse(raw)
184-
parsed.is_a?(Hash) ? parsed["value"] : raw
185-
rescue JSON::ParserError
186-
raw
187+
def hierarchy_format_custom_field?(custom_field_id)
188+
custom_field = @model.available_custom_fields.find { |cf| cf.id.to_s == custom_field_id }
189+
custom_field&.field_format.in?(%w[hierarchy weighted_item_list])
187190
end
188191

189192
def component(enforce_edit_mode: false)

0 commit comments

Comments
 (0)