Question

I have simple jbuilder view

json.id pharmaceutic.id
json.name pharmaceutic.name
json.dosage pharmaceutic.dosage.name

When pharmaceutic.dosage => nil

My rendered json looks like below:

{"id":1,"name":"HerzASS ratiopharm","dosage":null}

I would like set up for all jBuilder views that when some attribute is nil it should be rendered as empty string.

{"id":1,"name":"HerzASS ratiopharm","dosage":""}

How to achieve that?

Was it helpful?

Solution

nil.to_s #=> "" so, you can simply add .to_s

json.id pharmaceutic.id
json.name pharmaceutic.name.to_s
json.dosage pharmaceutic.dosage.name.to_s

OTHER TIPS

To extend on the accepted answer, here's a simple proxy class to do just that:

class Proxy

  def initialize(object)
    @object = object
  end

  def method_missing method, *args, &block
    if @object.respond_to? method
      @object.send(method, *args, &block).to_s
    else
      super method, *args, &block
    end
  end

  def respond_to? method, private = false
    super(method, private) || @object.respond_to?(method, private)
  end

end

class Roko < Struct.new(:a, :b, :c)
end

# instantiate the proxy instance by giving it the reference to the object in which you don't want nils
roko = Proxy.new(Roko.new)

puts roko.a.class # returns String even though :a is uninitialized
puts roko.a       # returns blank

json.dosage pharmaceutic.dosage.name.to_s

This will not work if pharmaceutic is nil. you can simply do

json.dosage pharmaceutic.dosage.name unless pharmaceutic.dosage.nil?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top