John Feminella
John Feminella

Reputation: 311436

How can I extract a Ruby `instance_eval` invocation into a method?

I have this Ruby code for a Padrino application:

module Filters
  def self.authorize_admin
    proc { halt(401) unless current_user.admin? }
  end
end

App.controllers :secrets do
  before :show, &Filters.authorize_admin
  # ...
end

When the secrets controller receives a request on the show route, it will run the authorize_admin filter.

If I want this rule to apply to every route instead, I might write this:

before { instance_eval &Filters.authorize_admin }

I'd like to extract this to a method in Filters instead, so that I can just write:

before { Filters.only_administrators }

What's the right way to do that?

Upvotes: 1

Views: 71

Answers (1)

John Feminella
John Feminella

Reputation: 311436

I wound up doing this:

module Filters
  def self.authorize_admin
    proc { halt(401) unless current_user.admin? }
  end

  def self.filter(controller, filter)
    filter_method = method(filter.to_sym)
    controller.instance_eval &(filter_method.call)
  end
end

and you now invoke it like:

Filters.filter(self, :authorize_admin)

Upvotes: 1

Related Questions