gpt4 book ai didi

ruby - 在 Ruby 的 DSL 中使用 procs

转载 作者:太空宇宙 更新时间:2023-11-03 18:00:58 24 4
gpt4 key购买 nike

为了方便用户和更干净的代码,我想编写一个可以像这样使用的类:

Encoder::Theora.encode do
infile = "path/to/infile"
outfile = "path/to/outfile"
passes = 2
# ... more params
end

现在的挑战是,让这些参数在我的编码方法中可用。

module Encoder
class Theora
def self.encode(&proc)
proc.call
# do some fancy encoding stuff here
# using the parameters from the proc
end
end
end

这种方法行不通。调用 Proc 时,不会在 Theora 类的上下文中评估变量。通常我想使用 method_missing 将每个参数放入类 Theora 的类变量中,但我没有找到正确的入口方式。

谁能指出我正确的方向?

最佳答案

我不确定是否可以让 DSL 使用赋值,我认为 Ruby 解释器将始终假定 infile in infile = 'path/to/something' 是该上下文中的局部变量(但可以使 self.infile = 'path/to/something' 起作用)。但是,如果您可以在没有这些特定细节的情况下生活,您可以像这样实现您的 DSL:

module Encoder
class Theora
def self.encode(&block)
instance = new
instance.instance_eval(&block)
instance
end

def infile(path=nil)
@infile = path if path
@infile
end
end
end

并像这样使用它:

Encoder::Theora.encode do
infile 'path/somewhere'
end

(类似地实现其他属性)。

关于ruby - 在 Ruby 的 DSL 中使用 procs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4756647/

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