Scope of Constants in Ruby Modules

Posted by user204078 on Stack Overflow See other posts from Stack Overflow or by user204078
Published on 2010-04-21T23:41:42Z Indexed on 2010/04/21 23:43 UTC
Read the original article Hit count: 136

Filed under:
|
|
|

I'm having a little problem with constant scope in mixin modules. Let's say I have something like this

module Auth

  USER_KEY = "user" unless defined? USER_KEY

  def authorize
    user_id = session[USER_KEY]
  def

end

The USER_KEY constant should default to "user" unless it's already defined. Now I might mix this into a couple of places, but in one of those places the USER_KEY needs to be different, so we might have something like this

class ApplicationController < ActionController::Base

  USER_KEY = "my_user"

  include Auth

  def test_auth
    authorize
  end

end

I would expect that USER_KEY would be "my_user" when used in authorize, since it's already defined, but it's still "user", taken from the modules definition of USER_KEY. Anyone have any idea how to get authorize to use the classes version of USER_KEY?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about rails