使用JBuilder嵌套对象

时间:2018-10-12 13:07:38

标签: ruby-on-rails jbuilder

我有一个对象,该对象具有一个to_builder函数,能够动态创建JSON,并且可以正常工作。当我想包含另一个具有to_builder方法的对象时,麻烦就来了。

头等舱

class Discovery
  def initialize(shower)
    @shower = shower
  end

  def  to_builder
    Jbuilder.new do |json|
      json.friendlyName @shower.name
      json.displayCategories ['OTHER']
      json.cookie {}
      json.capabilities do
        json.child! do
          json.type 'AlexaInterface'
          json.interface 'Alexa'
          json.version '3'
        end
        Discovery::CustomIntent.new.to_builder.target!
        json.child!{Discovery::CustomIntent.new.to_builder}
      end
    end
  end
end

第二堂课

class Discovery::CustomIntent
  def initialize
    @intents = %w(ShowerName ShowerOn ShowerOff ShowerPreset AMAZON.CancelIntent AMAZON.HelpIntent AMAZON.StopIntent)
  end

  def to_builder
    Jbuilder.new do |json| 
      json.type 'AlexaInterface'
      json.interface 'Alexa.CustomIntent'
      json.version '3'
      json.configuration do
        json.supportedIntents do
          json.(@intents) do |intent|
            json.name intent
          end
        end
      end
    end
  end
end

每当我执行Discovery.new(shower).to_builder.target!之类的操作时,我要添加的内部对象始终只是空的。

"{\"friendlyName\":\"Demo Shower\",\"displayCategories\":[\"OTHER\"],\"capabilities\":[{\"type\":\"AlexaInterface\",\"interface\":\"Alexa\",\"version\":\"3\"},{}]}"

0 个答案:

没有答案