A.10. 解析数组
在编写或修改模板时,您可能会遇到返回数组的变量。例如,与网络接口相关的主机变量,如 @host.interfaces
或 @host.bond_interfaces
,返回数组中分组的接口数据。要提取特定接口的参数值,请使用 Ruby 方法解析数组。
查找正确的方法来解析阵列
以下流程是一个示例,您可以使用它来查找模板中解析数组的相关方法。本例中使用了报告模板,但步骤适用于其他模板。
若要检索内容主机的 NIC,在本示例中使用
@host.interfaces
变量返回类值,然后使用该方法查找方法来解析数组。输入示例:
<%= @host.interfaces -%>
渲染示例:
<Nic::Base::ActiveRecord_Associations_CollectionProxy:0x00007f734036fbe0>
-
在 Create Template 窗口中,单击 Help 选项卡,再搜索
ActiveRecord_Associations_CollectionProxy
和Nic::Base
类。 对于
ActiveRecord_Associations_CollectionProxy
,在 Allowed method 或 members 列中,您可以查看以下方法来解析数组:[] each find_in_batches first map size to_a
对于
Nic::Base
,在 Allowed method 或 members 列中,您可以查看以下方法来解析阵列:alias? attached_devices attached_devices_identifiers attached_to bond_options children_mac_addresses domain fqdn identifier inheriting_mac ip ip6 link mac managed? mode mtu nic_delay physical? primary provision shortname subnet subnet6 tag virtual? vlanid
要迭代接口数组,请在 ERB 语法中添加相关的方法:
输入示例:
<% load_hosts().each_record do |host| -%> <% host.interfaces.each do |iface| -%> iface.alias?: <%= iface.alias? %> iface.attached_to: <%= iface.attached_to %> iface.bond_options: <%= iface.bond_options %> iface.children_mac_addresses: <%= iface.children_mac_addresses %> iface.domain: <%= iface.domain %> iface.fqdn: <%= iface.fqdn %> iface.identifier: <%= iface.identifier %> iface.inheriting_mac: <%= iface.inheriting_mac %> iface.ip: <%= iface.ip %> iface.ip6: <%= iface.ip6 %> iface.link: <%= iface.link %> iface.mac: <%= iface.mac %> iface.managed?: <%= iface.managed? %> iface.mode: <%= iface.mode %> iface.mtu: <%= iface.mtu %> iface.physical?: <%= iface.physical? %> iface.primary: <%= iface.primary %> iface.provision: <%= iface.provision %> iface.shortname: <%= iface.shortname %> iface.subnet: <%= iface.subnet %> iface.subnet6: <%= iface.subnet6 %> iface.tag: <%= iface.tag %> iface.virtual?: <%= iface.virtual? %> iface.vlanid: <%= iface.vlanid %> <%- end -%>
渲染示例:
host1.example.com iface.alias?: false iface.attached_to: iface.bond_options: iface.children_mac_addresses: [] iface.domain: iface.fqdn: host1.example.com iface.identifier: ens192 iface.inheriting_mac: 00:50:56:8d:4c:cf iface.ip: 10.10.181.13 iface.ip6: iface.link: true iface.mac: 00:50:56:8d:4c:cf iface.managed?: true iface.mode: balance-rr iface.mtu: iface.physical?: true iface.primary: true iface.provision: true iface.shortname: host1.example.com iface.subnet: iface.subnet6: iface.tag: iface.virtual?: false iface.vlanid: