I have to work with an legacy app and have to rewrite the old (PHP base)rest api. In the old api, when an attribute was null, it became an empty string.
Rails however just returns a null, which breaks the app. Rewriting the app is not the solution (even it this would be the cleanest way). Also in the old api, the other values are strings to (integers, booleans, numbers). So I was wondering, how can I do a to_s on every attribute witihout overriding every attribute ofcourse. I'm using active model serializer.
A little metaprogramming should help:
class MySerializer < ActiveModel::Serializer
[:id, :attr1, :attr2, :attr2].each do |attr|
# Tell serializer its an attribute
attribute attr
# Define a method with the same name as the attribute that calls the
# underlying object and to_s on the result
define_method attr do
object.send(attr).to_s
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With