Note that there are some explanatory texts on larger screens.

plurals
  1. POImplement Apect-oriented-like nested around filters with Ruby?
    primarykey
    data
    text
    <p>I'm trying to write a class that supports nested around filters without introducing an Aspect-oriented library.</p> <pre><code>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 {|&amp;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(&amp;blk) prior_around_filter = @around_filter @around_filter = #??mystery code here?? refers to prior_around_filter end end </code></pre> <p>The goal is to be able to add any number of around filters:</p> <pre><code>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 #=&gt; orange, strawberry, done, blueberry, grape </code></pre> <p>I know there are a bunch of holes in the example. I wrote only enough to covey the general direction, distilling from a much larger actual class.</p> <p>Although I prefer <code>yield</code> syntax, I'm not opposed to block references:</p> <pre><code>foo.add_around_filter do |&amp;blk| puts 'orange' blk.call puts 'grape' end </code></pre> <p>I got this working only with a single around filter. I tried lots of things with nesting, but never cracked the puzzle. If you have a solution, I'd appreciate it a bunch! </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload