ruby - Chef : no implicit conversion of String into Integer TypeError

标签 ruby search chef-infra

我写了一个像这样的小型 Chef 库:

module Test
  module Search
    extend self

    def single_node(type, value)
      result = Chef::Search::Query.new.search(:node, "#{type}:#{value}",
                                              filter_result: {
                                                'name' => ['name']
                                              }).map { |n| n['name'] }.first
      return result
    end

  end
end

针对它运行测试代码时出现以下错误:

TypeError
---------
no implicit conversion of String into Integer

         1:  module Test
         2:    module Search
         3:      extend self
         4:      def single_node(type, value)
         5:        result = Chef::Search::Query.new.search(:node, "#{type}:#{value}",
         6:                                                filter_result: {
         7:                                                  'name' => ['name']
         8>>                                               }).map { |n| n['name'] }.first
         9:        return result
        10:      end


        13:  end
        14:

经过一番尝试后,我发现搜索包含以下信息:

[[{"name"=>"influxdb.example.org"}], 0, 1].

这看起来很奇怪,因为在 Chef DSL 中搜索时使用的搜索选项会返回不同的东西。

最佳答案

在您调用的 Recipe 中执行搜索时 the search method in recipe DSL ,在将结果发回之前已经对结果进行了迭代。

当您调用 Chef::Sarch::Query.new.search 时,您正在调用 underlying method脱离 dsl 帮助程序,如果您不将 block 传递给处理结果的方法,则必须自己迭代结果。

你最终得到 here它返回一个包含查询结果数组的数组,以及结果的开始和大小(用于 UI 上的分页)。

所以@Oleander 已经给出了最终答案,在 map 之前调用 first,在结果部分调用 map返回(第一个数组条目)忽略分页变量。

或者要获得与 Recipe DSL 中相同的行为,请像这样使用 Chef::DSL::DataQuery:

require 'chef/dsl/data_query'

module Test
  module Search
    extend self
    include Chef::DSL::DataQuery

    def single_node(type, value)
      result = search(:node, "#{type}:#{value}",
                             filter_result: {
                               'name' => ['name']
                             }).map { |n| n['name'] }.first
      return result
    end
  end
end

关于缩短代码的相同想法:

require 'chef/dsl/data_query'

module Test
  module Search
    extend self
    include Chef::DSL::DataQuery

    def single_node(type, value)
      return search(:node, "#{type}:#{value}",
                             filter_result: {
                               'name' => ['name']
                             }).first['name']
    end
  end
end

它也返回第一个结果并获取它的名称,应该会更快一些,因为它不必“子集化”所有条目,而只需对第一个条目进行“子集化”。

关于ruby - Chef : no implicit conversion of String into Integer TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33987590/

相关文章:

ruby - 从Datamapper开始,关联问题

ruby - 一些“Fixnum”属性

python - Algolia reindex 命令在 urllib3 中失败并出现异常

javascript - 使用输入框启动谷歌搜索

chef-infra - 在正在运行的系统上更改Vagrant端口转发

python - python的进化路线图是什么

ruby - 将 json 解析为 ruby​​ 对象

c# - 字符串的不区分大小写的哈希 (SHA)

chef-infra - Chef : No available formula with the name "httpd"

ssh - Chef-client 中途死亡