Dynamically requiring files?
Does anyone know enough about Ruby's require
to tell me if the following is valid syntax:
class Something
开发者_JAVA技巧def initialize(mode)
case mode
when :one then require 'some_gem'
when :two then require 'other_gem'
end
end
end
s = Something.new
If so, will the require
place the gem into the global namespace as it would when at the top of the file?
If so, would the require place the gem into the global namespace as the same require at the top of the file would?
Yes. require
doesn't have scope, while load
does.
Yes it's perfectly valid and works as expected because require isn't scoped
Require pulls in the code from the specified file and attempts to use it in-place - that might mean that it isn't sensible to do but yes it can be done.
The local method scope would be unaffected and any class definition etc would be at the expected scope
精彩评论