Skip to content

Instantly share code, notes, and snippets.

@mitchellh
Created July 15, 2012 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitchellh/3118148 to your computer and use it in GitHub Desktop.
Save mitchellh/3118148 to your computer and use it in GitHub Desktop.
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
@paul
Copy link

paul commented Jul 15, 2012

There's problems the other way, too:

module Foo
  # stuff
end

class Foo::Bar
  # other stuff
end

...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 say module Foo; class Bar and fix them.

@mitchellh
Copy link
Author

👍

@pixeltrix
Copy link

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