From: Jeremy Bopp Date: 2010-10-27T06:06:40+09:00 Subject: Re: require in instance_eval On 10/26/2010 2:33 PM, unexist wrote: > > ---- On Tue, 26 Oct 2010 18:35:58 +0200 Jeremy Bopp wrote ---- > >> You can call require from anywhere, be it within a class definition, a >> method, or even an eval statement. In all cases the general expectation >> is that require loads the file into the global namespace rather than >> into the scope of the calling code. > > Yeah this makes sense, but it still surprised me. I thought it will require it in the > current scope. So for proper sandboxing you need to change require. It would seem so, but you need to take care with that since your users may still expect to use require to load other extensions. >> Have you tried loading the contents of the file as a string and then >> passing the string to eval rather than call require on the file? I >> think that might do what you want. > > I am using ruby as embedded scripting language in my window manager and for > the config file. Recently I decided moving the DSL parts of the config into a kind of > sandbox for evaling and to avoid polluting the global namespace. > > Some of the users splitted their config into several parts and included them with > require and require_relative. Maybe your DSL can provide an alternative to require that does what you want while leaving require alone. It would break compatibility with some existing configurations that use require and require_relative, but you could have a deprecation period where using those methods would produce a warning and then fall back to the DSL's alternative. >> What exactly is the error message when you try to use require_relative? > > When I use the example from before and just change the require to > require_relative in read.rb I get this error: > > read.rb:3:in `require_relative': cannot infer basepath (LoadError) > from read.rb:3:in `
' > from foobar.rb:11:in `instance_eval' > from foobar.rb:11:in `
' > > Which probably makes sense, since the basepath is undefined, but it a pita. ;) That makes sense, and now I see that this is where you meant that adding a file path argument to instance_eval didn't help. You were hoping that doing so would give require_relative a basepath from which to start searching. I wonder if the inability to use require_relative from within an eval should be considered a bug. Maybe require_relative should support an argument for an explicit basepath, at least as a workaround. -Jeremy