diff --git a/lib/avo/fields/code_field.rb b/lib/avo/fields/code_field.rb index 68c0d6618..6de470c13 100644 --- a/lib/avo/fields/code_field.rb +++ b/lib/avo/fields/code_field.rb @@ -11,6 +11,11 @@ class CodeField < BaseField def initialize(id, **args, &block) hide_on :index + if args[:pretty_generated] + args[:format_using] ||= -> { value.blank? ? value : JSON.pretty_generate(value) } + args[:update_using] ||= -> { JSON.parse(value) } + end + super(id, **args, &block) @language = args[:language].present? ? args[:language].to_s : "javascript" diff --git a/spec/dummy/app/avo/resources/city.rb b/spec/dummy/app/avo/resources/city.rb index 47c64990f..7860dc224 100644 --- a/spec/dummy/app/avo/resources/city.rb +++ b/spec/dummy/app/avo/resources/city.rb @@ -61,19 +61,7 @@ def base_fields as: :trix, attachment_key: :description_file, visible: -> { resource.params[:show_native_fields].blank? } - field :metadata, - as: :code, - format_using: -> { - if view.edit? - JSON.generate(value) - else - value - end - }, - update_using: -> do - ActiveSupport::JSON.decode(value) - rescue JSON::ParserError - end + field :metadata, as: :code, pretty_generated: true field :created_at, as: :date_time, filterable: true end diff --git a/spec/system/avo/code_field_spec.rb b/spec/system/avo/code_field_spec.rb index 595a61c33..ce05da05f 100644 --- a/spec/system/avo/code_field_spec.rb +++ b/spec/system/avo/code_field_spec.rb @@ -77,6 +77,49 @@ end end + describe "with pretty_generated option for a JSON code field" do + let(:metadata) do + { + name: "New York", + country: "United States", + population: 8419600, + coordinates: { + latitude: 40.7128, + longitude: -74.006 + }, + timezone: "America/New_York", + climate: { + type: "humid subtropical", + average_temperature_celsius: 13.1 + }, + points_of_interest: [ + "Statue of Liberty", + "Central Park", + "Empire State Building" + ] + } + end + + it "correctly formats JSON code on create / edit and displays it in a pretty way on the show page" do + visit "/admin/resources/cities/new" + wait_for_loaded + + within find_field_element("metadata") do + fill_in_editor_field(JSON.pretty_generate(metadata)) + end + + save + + json_text = page.evaluate_script('document.querySelector(".CodeMirror").CodeMirror.getValue()') + expect(JSON.parse(json_text, symbolize_names: true)).to eq(metadata) + + click_on "Edit" + + json_text = page.evaluate_script('document.querySelector(".CodeMirror").CodeMirror.getValue()') + expect(JSON.parse(json_text, symbolize_names: true)).to eq(metadata) + end + end + def fill_in_editor_field(text) within ".CodeMirror" do current_scope.click