用 Ruby 编写类似 Thor gem 的 DSL?

发布于 2024-10-08 03:45:09 字数 767 浏览 4 评论 0原文

我试图弄清楚 Thor gem 如何创建这样的 DSL(自述文件中的第一个示例)

class App < Thor                                                 # [1]
  map "-L" => :list                                              # [2]

  desc "install APP_NAME", "install one of the available apps"   # [3]
  method_options :force => :boolean, :alias => :string           # [4]
  def install(name)
    user_alias = options[:alias]
    if options.force?
      # do something
    end
    # other code
  end

  desc "list [SEARCH]", "list all of the available apps, limited by SEARCH"
  def list(search="")
    # list everything
  end
end

具体来说,它如何知道将 descmethod_options 调用映射到哪个方法?

I'm trying to figure out how the Thor gem creates a DSL like this (first example from their README)

class App < Thor                                                 # [1]
  map "-L" => :list                                              # [2]

  desc "install APP_NAME", "install one of the available apps"   # [3]
  method_options :force => :boolean, :alias => :string           # [4]
  def install(name)
    user_alias = options[:alias]
    if options.force?
      # do something
    end
    # other code
  end

  desc "list [SEARCH]", "list all of the available apps, limited by SEARCH"
  def list(search="")
    # list everything
  end
end

Specifically, how does it know which method to map the desc and method_options call to?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

音盲 2024-10-15 03:45:09

desc 非常容易实现,诀窍是使用 Module.method_added

class DescMethods
  def self.desc(m)
    @last_message = m
  end

  def self.method_added(m)
    puts "#{m} described as #{@last_message}"
  end
end

任何继承于 DescMethods 的类都会有一个 desc 方法如 Thor。对于每种方法,都会打印一条消息,其中包含方法名称和说明。例如:

class Test < DescMethods
  desc 'Hello world'
  def test
  end
end

当定义此类时,将打印字符串“test描述为Hello world”。

desc is pretty easy to implement, the trick is to use Module.method_added:

class DescMethods
  def self.desc(m)
    @last_message = m
  end

  def self.method_added(m)
    puts "#{m} described as #{@last_message}"
  end
end

any class that inherits from DescMethods will have a desc method like Thor. For each method a message will be printed with the method name and description. For example:

class Test < DescMethods
  desc 'Hello world'
  def test
  end
end

when this class is defined the string "test described as Hello world" will be printed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文