-
Notifications
You must be signed in to change notification settings - Fork 440
Description
In ERB
templates, ActionText
attributes are automatically cast to strings, thus rendering their HTML contents. However, in jbuilder this is not the case and we have to call to_s
on every action_text attribute, which is verbose and easy to forget.
What's worse is that it prevents passing an object and attributes list to json.extract!
or an enumarable and a list of attributes to json.array!
.
Is there a way to specify a formatter that would work on action_text fields only? Or perhaps adding an opt-in mechanism in Jbuilder::_extract_method_values
to handle this situation?
I know this would mean tying adding ActionText
-specific code to Jbuilder
but given that these two libraries are generally used together in Rails, this could make sense. I'd be happy to take a stab at a PR if you think this is a good idea.
Example with json.extract!
# Doesn't work as expected:
json.extract! my_model, :id, :updated_at, :some_rich_text
{
"id": 1,
"updated_at":"2022-05-23T10:08:38.784+02:00",
"some_rich_text":
{
"id":1,
"name":"some_rich_text",
"body":"<div>Rich text contents</div>",
"record_type":"MyModel",
"record_id":20,
"created_at":"2022-05-23T10:08:38.784+02:00",
"updated_at":"2022-05-23T10:08:38.784+02:00"
}
}
# Works:
json.extract! my_model, :id, :updated_at
json.some_rich_text my_model.some_rich_text.to_s
{
"id": 1,
"updated_at":"2022-05-23T10:08:38.784+02:00",
"some_rich_text":"<div>Rich text contents</div>"
}
Example with json.array!
# Doesn't work as expected:
json.array! my_collection, :id, :updated_at, :some_rich_text
[
{
"id": 1,
"updated_at":"2022-05-23T10:08:38.784+02:00",
"some_rich_text":
{
"id":1,
"name":"some_rich_text",
"body":"<div>Rich text contents</div>",
"record_type":"MyModel",
"record_id":20,
"created_at":"2022-05-23T10:08:38.784+02:00",
"updated_at":"2022-05-23T10:08:38.784+02:00"
}
}
]
# Works:
json.array! my_collection do |item|
json.extract! item, :id, :updated_at
json.some_rich_text item.some_rich_text.to_s
end
[
{
"id": 1,
"updated_at":"2022-05-23T10:08:38.784+02:00",
"some_rich_text":"<div>Rich text contents</div>"
}
]