Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Rails-like before filter in Sinatra?

Tags:

ruby

sinatra

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.

like image 224
B Seven Avatar asked Nov 21 '25 17:11

B Seven


1 Answers

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:

class Foo < Sinatra::Base

  before do
    "Do something"
  end

  get '/' do
    "Hello World"
  end
end

class Bar < Sinatra::Base

  before do
    "Do something else"
  end

  get '/' do
    "Hello World"
  end
end

In your config.rb file,

require 'foo.rb'
require 'bar.rb'

map '/foo' do
  run Foo
end

map '/bar' do
  run Bar
end

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).

like image 138
Kashyap Avatar answered Nov 23 '25 23:11

Kashyap