Sean Schofield
Sean Schofield

Reputation: 597

Can I "Unload" a Rails Metal Class after one time use?

I've got a Rails metal class that basically does a one time check to make sure there is an admin user in the system, if not, it redirects user to create one. Right now I'm using the rack session to prevent double checking but that seems to have the following problems:

I wonder if its possible to direct Rails to "remove" or "unload" the class from the chain. Can this be done safely? Any other suggestions?

Upvotes: 0

Views: 236

Answers (1)

cwninja
cwninja

Reputation: 9768

A simplest solution (although not quite as clean) would be to store the fact that an admin user exists in the class.

class EnsureAdminUser
  def self.call(env)
    if @admin_defined or Admin.any?
      @admin_defined = true
      [404, {"Content-Type" => "text/html"}, "Not Found"]
    else
      …
    end
  end
end

This saves you the DB hit on each request.

To actually delete the metal you will need to do something a bit more radical (and evil):

ObjectSpace.each_object(Rails::Rack::Metal){|metal_handler|
  metal_handler.instance_eval{ @metals.delete(EnsureAdminUser) }
}

Upvotes: 2

Related Questions