Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Stick this in the lib directory and use it instead of SimpleDelegator to solve this issue: http://thepugautomatic.com/2014/03/simpledelegator-autoloading-issues-with-rails/
# See:
# * http://thepugautomatic.com/2014/03/simpledelegator-autoloading-issues-with-rails/
# * https://groups.google.com/forum/#!topic/rubyonrails-core/PjGUK72BmFA
# * https://gist.github.com/henrik/9314943
require "delegate"
class RailsCompatibleSimpleDelegator < SimpleDelegator
def self.const_missing(name)
if ::Object.const_defined?(name)
# This is what SimpleDelegator usually does.
# Load top-level constants even though SimpleDelegator inherits from BasicObject.
::Object.const_get(name)
else
# Rails autoloading.
::ActiveSupport::Dependencies.load_missing_constant(self, name)
end
end
end
class MyFixtureDelegator::Subthing
end
class MyFixtureDelegator < RailsCompatibleSimpleDelegator
end
require "spec_helper"
require "rails_compatible_simple_delegator"
# So Rails autoloading looks in unit/fixtures.
require "active_support/dependencies"
ActiveSupport::Dependencies.autoload_paths << File.join(File.dirname(__FILE__), "../fixtures")
describe RailsCompatibleSimpleDelegator do
it "mostly works like SimpleDelegator" do
delegator = RailsCompatibleSimpleDelegator.new("foo")
expect(delegator.reverse).to eq "oof"
end
it "can look up standard library constants without an explicit '::' (like SimpleDelegator)" do
expect(RailsCompatibleSimpleDelegator::File).to eq ::File
end
it "can autoload its own namespaced constants (like Rails autoloading)" do
expect(MyFixtureDelegator::Subthing).to be_present
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment