Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails active model serializer, how to return empty string instead of null

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.

like image 812
Jareish Avatar asked Nov 11 '13 08:11

Jareish


1 Answers

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
like image 131
Jerry Clinesmith Avatar answered Sep 24 '22 02:09

Jerry Clinesmith