我正在尝试将以下返回的json初始化为对象(环境),但我无法弄清楚如何分配子哈希(即设置)部分。
{"deploymentEnvironmentId" => 54321,
"accountId" => 1234,
"provider" => "Agent",
"name" => 'test',
"settings" =>
{ "providerSettings" =>
[{
"name" => "test_setting",
"value" => {
"isEncrypted" =>false,
"value" => "myaccount"
}
}]
}
}
我尝试添加一个公共发送方式init方法,但在查询时不会撤回提供程序部分
@environment.settings[provider_settings].first[name]
class Environment
def initialize(options = {})
if options
options.each { |k,v| public_send("#{k}=",v)}
end
end
def id
@deploymentEnvironmentId
end
def settings(settings = {})
options.settings.each { |k,v| public_send("#{k}=",v)}
end
attr_accessor :deploymentEnvironmentId
attr_accessor :accountId
attr_accessor :name
attr_accessor :provider
attr_accessor :projectsMode
attr_accessor :created
attr_accessor :updated
attr_accessor :settings
end
答案 0 :(得分:1)
所以我错误地访问了内部数组。得到this post和IRB的一些帮助。
以@environment.settings['providerSettings'].first['name'])
方式访问它是一种享受。
我坚持从json传回来的变量,因为他们现在不按照约定, 工作。
感谢@maicher指出我正在设置,然后覆盖@settings
答案 1 :(得分:0)
您定义了settings
方法,然后通过调用attr_accessor :settings
来覆盖它。
很可能你在options.settings.each
行有一个错误。我认为它应该从方法论证中调用settings
。
您可以尝试修复它,但可能会有更多错误。
而是试图解决这个问题,我建议明确设置所有选项。
class Environment
class Error < StandardError; end
def initialize(options = {})
self.deployment_environment_id = options.fetch('deploymentEnvironmentId')
self.account_id = options.fetch('accountId')
# ...
self.name = options.fetch('settings').fetch('providerSettings').first.fetch('name')
# ...
rescue KeyError => e
raise Error, "Options hash is invalid. #{e}"
end
def id
deployment_environment_id
end
attr_accessor :deployment_environment_id
attr_accessor :account_id
attr_accessor :name
attr_accessor :provider
attr_accessor :projects_mode
end
我们在这里可以看到什么?
属性设置为expicitly。
属性&#39;名称遵循ruby约定命名(蛇案例)。
使用fetch而不是[]
使得无效哈希上的初始化失败(通过引发KeyError
),因此它可以保证您最终不会对对象进行半初初化
KeyError
可以获救,以指定自定义错误消息。
可能它并不完全是您所要求的,但我相信这种方法会让其他开发人员和将来的代码更具可读性。