Skip to content

Instantly share code, notes, and snippets.

@timriley
Created August 22, 2018 23:28
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 timriley/e76d99ee8fbc69633482bd0d48667b18 to your computer and use it in GitHub Desktop.
Save timriley/e76d99ee8fbc69633482bd0d48667b18 to your computer and use it in GitHub Desktop.
Methods defined in Rakefile added to every object, via Kernel
$ rake testing:test
Methods on Kernel:
[:foo_from_rake_namespace, :bar_from_rake_namespace, :foo_from_rake_top_level]
Methods on class (and source locations):
:foo_from_rake_namespace => ["/Users/tim/Source/dry-rb/_bugs/rake_test/Rakefile", 9]
:bar_from_rake_namespace => ["/Users/tim/Source/dry-rb/_bugs/rake_test/Rakefile", 13]
:foo_from_rake_top_level => ["/Users/tim/Source/dry-rb/_bugs/rake_test/Rakefile", 4]
class MyClass
end
def foo_from_rake_top_level
"foo"
end
namespace :testing do
def foo_from_rake_namespace
"foo"
end
def bar_from_rake_namespace
"bar"
end
task :test do
puts "Methods on Kernel:"
p Kernel.private_methods.grep(/from_rake/)
puts
puts "Methods on class (and source locations):"
my_obj = MyClass.new
my_obj.private_methods.grep(/from_rake/).each { |meth|
puts "#{meth.inspect} => #{my_obj.method(meth).source_location.inspect}"
}
end
end
@timriley
Copy link
Author

timriley commented Aug 22, 2018

OK, it turns out this is nothing to do with Rake, it's just plain Ruby behaviour.

Define a method in the global namespace, and it goes onto Kernel, and therefore becomes a private method for every object created henceforth.

class MyClass
end

def top_level_method
  "hi"
end

p MyClass.new.private_methods.grep(/top_level/)
# => [:top_level_method]

tl;dr don't define unscoped methods in Rakefiles! 😬

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment