class Foo
def do_before
...
end
def do_something
...
Is there a way to run do_before
method before each other method in the Foo
class (like do_something
)?
It seems that the Sinatra before
block runs before each HTTP request, which has nothing to do with this class.
EDIT: As Michael pointed out in the comments, the only similar functionality that Rails offers is in the Controller. However, both Rails and Sinatra offer something similar to this functionality.
You can also use a bit of meta-programming to create a before filter. For instance:
In this case, the
preprocess_method
(that is the do_before on your example) will be called before each call to any instance method defined within the Foo class.As iain pointed out in the comments, the example you specify is not specific to Rails/Sinatra. I'm assuming you want before filter like the ones in Rails and this is what Sinatra offers:
Sinatra's modular apps:
In your
config.rb
file,This is the nearest analogy for a Rails controller in Sinatra. Create more classes like this and you'll have a similar functionality (similar, but may not be the same as you might expect in Rails world).
Not knowing what you're doing makes it difficult to know how to answer, but to increase the information out there on the web;) I'll give an alternative to @fmendez's answer:
output: