在红宝石类中调用刀 [英] invoking knife in a ruby class

查看:74
本文介绍了在红宝石类中调用刀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想围绕刀创建一个不错的包装器类,以允许程序以可读的方式运行刀命令。我目前正在尝试使用Chef gem中的knife.rb文件作为成功的指南。但是,我在关闭编辑器时遇到了问题。如果我运行以下代码:

I'd like to create a nice wrapper class around knife to allow a program to run knife commands in a readable manner. I'm currently trying to use the knife.rb file in the chef gem as a guide to some success. However, I'm having an issue turning off the editor. If I run the following code:

    require 'chef/knife'
    knife = Chef::Knife.new
    knife.run(['client', 'create', 'new-client'], '--disable-editing')

它会导致以下错误:

    NoMethodError: undefined method `merge!' for "--disable-editing":String

任何人都对如何成功执行此操作有任何想法?

Anyone have any ideas on how to do this successfully? Is there a library by chance that already exists that does what I need?

推荐答案

所以我能够解决这个问题。它确实确实需要一个哈希,但它希望它是Mixlib :: CLI类的子集。因此,这是通过编程程序通过刀创建客户端所需的代码:

So I was able to solve this problem. It does indeed want a hash, but it wants it to be a subset of the Mixlib::CLI class. So, this is the code needed to create a client via knife programmatically:

    class MyCLI
      include Mixlib::CLI
    end

    #Add the option for disable editing. If you look in knife help, it's --disable-editing
    MyCLI.option(:disable_editing, :long => "--disable-editing", :boolean => true)

    #instantiate knife object and add the disable-editing flag to it
    knife = Chef::Knife.new
    knife.options=MyCLI.options

    #set up client creation arguments and run
    args = ['client', 'create',  'new_client', '--disable-editing' ]  
    new_client = Chef::Knife.run(args, MyCLI.options)

这不是最优雅的解决方案,但它确实通过命令行使用了刀子,从而使某人免于拥有使用系统调用来使用它。

It's not the most elegant solution, but it does use knife via the command line and saves someone from have to use a system call to use it.

这篇关于在红宝石类中调用刀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆