【问题标题】:How to returns empty string instead of null in jbuilder views?如何在 jbuilder 视图中返回空字符串而不是 null?
【发布时间】:2013-08-02 11:35:24
【问题描述】:

我有简单的 jbuilder 视图

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

pharmaceutic.dosage => nil

我渲染的 json 如下所示:

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

我想为所有 jBuilder 视图设置当某些属性为 nil 时,它应该呈现为空字符串。

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

如何实现?

【问题讨论】:

  • 也许这样做? json.dosage pharmaceutic.dosage.name || "" 与此操作数如果 dosage.namenil 它将使用空字符串

标签: ruby-on-rails ruby json jbuilder


【解决方案1】:

nil.to_s #=> "" 所以,你可以简单地添加.to_s

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

【讨论】:

  • 这是一个很好的解决方案,但我正在寻找一个不需要为所有 500 个属性添加 to_s 的答案。
【解决方案2】:

为了扩展接受的答案,这里有一个简单的代理类来做到这一点:

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

【讨论】:

    【解决方案3】:

    json.dosage pharmaceutic.dosage.name.to_s

    如果 pharmaceutic 为 nil,这将不起作用。你可以简单地做

    json.dosage pharmaceutic.dosage.name unless pharmaceutic.dosage.nil?
    

    【讨论】:

      猜你喜欢
      • 2013-10-31
      • 1970-01-01
      • 2014-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-13
      • 2011-05-18
      • 1970-01-01
      相关资源
      最近更新 更多