Skip to content

Add pretty_generated option for code fields #3782

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
5 changes: 5 additions & 0 deletions lib/avo/fields/code_field.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
14 changes: 1 addition & 13 deletions spec/dummy/app/avo/resources/city.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
43 changes: 43 additions & 0 deletions spec/system/avo/code_field_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading