Created
July 15, 2012 18:52
-
-
Save mitchellh/3118148 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CONSTANT = "in <global>" | |
class Foo | |
CONSTANT = "in foo" | |
end | |
class Foo::Bar | |
puts CONSTANT # => "in <global>" | |
end | |
class Foo | |
class Bar | |
puts CONSTANT # => "in foo" | |
end | |
end |
👍
This quite often bites when developing namespaced engines for Rails, e.g:
class Blog::Post < ActiveRecord::Base
def self.recent
order("created_at DESC").limit(5)
end
end
class Blog::PostsController < Blog::ApplicationController
def index
# this fails because it's looking for Post in global scope
@posts = Post.recent
end
end
module Blog
class PostsController < ApplicationController
def index
# this works as it's looking for Post in Blog scope
@posts = Post.recent
end
end
end
It can get especially tricky when in development mode and constant autoloading is in effect - you end having to use require_dependency
to make sure that the constant you need is loaded properly.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There's problems the other way, too:
...and then you decide to change
Foo
from a module to a class, you don't have to go around to all your other files that saymodule Foo; class Bar
and fix them.