Skip to content

Instantly share code, notes, and snippets.

@mitchellh
Created July 15, 2012 18:52
Show Gist options
  • 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
@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