gpt4 book ai didi

ruby - 我如何确定方法选项的范围?

转载 作者:数据小太阳 更新时间:2023-10-29 08:05:23 26 4
gpt4 key购买 nike

我有一个解析 gem 的选项,它提供了用于创建命令的 DSL。在实践中,它通常看起来像这样:

option :ints,    Integer, arity: [1, -1], on_multiple: :append
option :floats, Float, arity: [1, -1], on_multiple: :append
option :complex, Complex, arity: [1, -1], on_multiple: :append

这些是类方法。正如您所看到的,不是很干。最好这样写:

scope arity: [1, -1], on_multiple: :append do
option :ints, Integer
option :floats, Float
option :complex, Complex
end

将提供给 scope 的选项散列透明地与提供给 option 的散列合并。那就是我被困的地方。我不确定将常用选项存储在哪里,以便以后可以合并它们。

有什么想法吗?


option 将所有内容转发给 Option#new:

def option(*args, &block)
# self is a class that represents a command
self.options << Option.new(*args, &block)
end

根据要求,这是代码,删除了支持 gem 的使用:

def initialize(key, *args, &block)
# Retrieve the options hash from the argument array.
options = args.last.is_a?(Hash) ? args.pop : {}

# The rest of the implementation...
type = args.find { |arg| arg.is_a? Module }

strings = args.flatten.select do |arg|
arg.is_a? String
end.group_by do |arg|
arg =~ Parser::Regexp::SWITCH ? :switches : :description
end

self.key = key
self.names = strings.fetch(:switches) { [ Option.name_from(key) ] }
self.description = options.fetch :description, strings.fetch(:description, []).first
self.on_multiple = options.fetch :on_multiple, :replace
self.arity = options.fetch :arity, nil
self.default = options.fetch :default, nil
self.required = options.fetch :required, false
self.type = type || String
self.handler = block
end

Original on GitHub .

最佳答案

看看Object#with_options来自 Rails,并将其滑动以供您自己使用。

关于ruby - 我如何确定方法选项的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10645006/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com