ruby 如何在recipe中的default.rb中获取数组中的值?

agxfikkp  于 2023-05-17  发布在  Ruby
关注(0)|答案(1)|浏览(73)

attributes/default.rb中,值以下面的格式声明。

default[:node][:action][:host_list] = [
  {
    :environment => 'dev',
    :application => 'appA',
    :server_name => 'serverA',
    :url => 'serverA.com'
  },
  {
    :environment => 'dev',
    :application => 'appB',
    :server_name => 'serverB',
    :url => 'serverB.com'
  },
  {
    :environment => 'test',
    :application => 'appA',
    :server_name => 'tserverA',
    :url => 'tserverA.com'
  },
  {
    :environment => 'test',
    :application => 'appB',
    :server_name => 'tserverB',
    :url => 'tserverB.com'
  }
]

从我的一个食谱中,如何从这个default.rb中检索server_nameurl的值(如所需)?
我从数据包中获取env和app值。我需要像server_name和url的其他值用于例如。在一个简单的put语句和一个HTTP调用中。
示例:
:environment = dev &:application = appA(从数据包读取值)
我需要从default.rb中的host_list声明中获得相应的:server_name和:url,以便获得如下值:

full_server_name = [:env]-[:app]-[:server_name] #=> dev-appA-serverA

puts :url #=> serverA.com
jgwigjjp

jgwigjjp1#

我们可以使用.select Ruby方法从哈希(数组)中找到匹配的值,并将其存储在变量中。然后我们可以使用这些变量来形成预期的输出。
例如,如您的问题所示,让我们将:environment作为dev,将:application作为appA

env = 'dev'
app = 'appA'

# first variable captures (two) hashes that have environment dev
r1 = node[:node][:action][:host_list].select {|r| r[:environment] == env}

# next variable collects the hash which contains appA
r2 = r1.select {|r| r[:application] == app}

# we can now use values from r2
full_server_name = "#{r2[0][:environment]}-#{r2[0][:application]}-#{r2[0][:server_name]}"

puts r2[0][:url]

请注意,我们必须使用数组索引0,因为您的原始属性是一个Hash数组。

相关问题