Question

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.

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top