gpt4 book ai didi

ruby - 使用 Ruby 实现类似面向 Apect 的嵌套过滤器?

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

我正在尝试编写一个支持嵌套过滤器的类,而无需引入面向方面的库。

class Foo
attr_accessor :around_filter

def initialize
#filters which wrap the following one are the ones with interesting logic
#vanilla do-nothing filter
@around_filter = lambda { yield } # or lambda {|&blk| blk.call}
end

def bar
#would execute the around filters however deeply nested, then "meaty code"
@around_filter.call do
#meaty code here
puts 'done'
end
end

#I expected to point only to the topmost filter, hoping to recurse
def add_around_filter(&blk)
prior_around_filter = @around_filter
@around_filter = #??mystery code here?? refers to prior_around_filter
end
end

目标是能够添加任意数量的环绕过滤器:

foo = Foo.new
foo.add_around_filter do
puts 'strawberry'
yield
puts 'blueberry'
end
foo.add_around_filter do
puts 'orange'
yield
puts 'grape'
end
foo.bar #=> orange, strawberry, done, blueberry, grape

我知道这个例子中有很多漏洞。我只写了足够的内容来传达总体方向,从更大的实际类中提炼出来。

虽然我更喜欢yield 语法,但我并不反对 block 引用:

foo.add_around_filter do |&blk|
puts 'orange'
blk.call
puts 'grape'
end

我只使用一个环绕过滤器就可以做到这一点。我尝试了很多关于嵌套的事情,但从未破解过这个难题。如果您有解决方案,我将不胜感激!

最佳答案

过滤器中的 yield 将尝试屈服于在其定义点定义的 block ,这不是您想要的。它将使用显式 block 形式(在 1.9 中),如下所示:

class Foo
attr_accessor :around_filter

def initialize
#filters which wrap the following one are the ones with interesting logic
#vanilla do-nothing filter
@around_filter = Proc.new{|&blk| blk.call }
end

def bar
#would execute the around filters however deeply nested, then "meaty code"
@around_filter.call do
#meaty code here
puts 'done'
end
end

#I expected to point only to the topmost filter, hoping to recurse
def add_around_filter(&filter)
prior_around_filter = @around_filter
@around_filter = Proc.new do |&blk|
filter.call do
prior_around_filter.call(&blk)
end
end
end
end

foo = Foo.new
foo.add_around_filter do |&blk|
puts 'strawberry'
blk.call
puts 'blueberry'
end
foo.add_around_filter do |&blk|
puts 'orange'
blk.call
puts 'grape'
end
foo.bar #=> orange, strawberry, done, blueberry, grape

关于ruby - 使用 Ruby 实现类似面向 Apect 的嵌套过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3047146/

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