Need help with callbacks

Hi, I’m messing around with Sinatra right now, and enjoying it a lot.
I’ve recently tried to integrate a little bit of Rails-y stuff with
Sinatra (mainly ActiveModel, ActiveSupport), and I’m not starting to
create my own little microframework based off Sinatra and those Rails
libraries.

All that said, I’m using ActiveSupport’s callbacks library that lets you
define callbacks for methods like this:

define_callbacks :index
set_callback :index, :after do
@some_value = true
end

def index
run_callbacks :index do
# normal index code goes here, is wrapped by callback block
end
end

This supports :after, :before and :around callbacks, where around
takes a lambda like this:

set callback :index, :around, lambda do |obj|
@value = true
res = yield # the normal index code
@value2 = true if res
end

I don’t want to repeat these steps each time I define callbacks in my
projects. I want something like this:

before_action :index do
@val = true
end

I tried to implement this and the results are a mess, even though
they work. The file that contains my code:


Lines 17-43 contain my implementation. How can I improve this code? How
did Rails go about their implementation of before_filters? How would you
approach this problem?

Thanks!

-Luke

P.S. Notice how in my code I had to run through all these hoops instead
of just redefining the original method because that would trigger
method_added again and go into infinite recursion deathloops!? Major
headache…

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs