#<URI::HTTPS:0x0000000404f3b8> 的未定义方法“gsub”

Undefined method `gsub' for #<URI::HTTPS:0x0000000404f3b8>

我正在尝试对用户输入的 url 使用 Http::get 请求。在一个食谱中,我有 url “https://company.in.example.net:port/ha". This recipe prints the subnets available. User will select the subnet and give it as input. Suppose user gives "100.1.100.1" then I need to append it to existing url and perform http::get action on that. So the new url should be "https://company.in.example.net:port/ha/100.1.100.1” 我写了以下脚本。

url = 'https://company.in.example.net:port/ha/'
ruby_block 'run_my_template_resource' do
   action :create
   block do
     puts "Enter subnet: "
     input = gets
     url = url + input
     puts url
     uri =  URI.parse(URI.encode(url.to_s))
     r = Chef::Resource::Template.new('default',run_context)
     r.path       '/etc/app.conf'
     r.source     'app.conf.erb'
     r.cookbook   'testbook'
     r.owner      'root'
     r.group      'root'
     r.mode       00600
     r.variables({
     my_id: Chef::HTTP.new(uri).get('/',{ 'user-principal' => 
 '{"userName":"user","password":"pass"}', 'Accept' => 'application/json', 
 'Content-Type' => 'application/json' })
    })
     r.run_action :create
   end
 end

此处 url 打印正确 url。当我 运行 食谱时,我收到错误 NoMethodError: undefined methodgsub' for #` 任何帮助将不胜感激。 谢谢:)

您的代码存在一些问题。

首先你会得到 URI::InvalidURIError: bad URI(is not URI?) 因为你传递的不是语义上有效的 URI。

url = 'https://company.in.example.net:port/ha/'

我怀疑您没有用实际端口号替换 :port

其次,您在接收用户输入时未删除尾随空格。您应该将您的行阅读为:

input = gets.chomp

否则你的输入会有一个尾随 \n,给你一个无效的 URI。

第三,如果您收到 gsub 错误,是因为 Chef 可能期望收到 String,而不是 URI 对象。您可以像这样轻松地将 URI 转换为字符串:

Chef::HTTP.new(uri.to_s)