Require file without executing code?

有些话、适合烂在心里 提交于 2019-12-03 05:57:45

Is it possible to load a file without having it to run the code?

No, everything in a ruby file is executable code, including class and method definitions (you can see this when you try to define a method inside an if-statement for example, which works just fine). So if you wouldn't execute anything in the file, nothing would be defined.

You can however tell ruby that certain code shall only execute if the file is run directly - not if it is required. For this simply put the code in question inside an if __FILE__ == $0 block. So for your example, this would work:

file.rb

def method
  puts "This won't be outputted."
end
if __FILE__ == $0
  puts "This will not be outputted."
end

main.rb

require "./file"

the if __FILE__ == $0 is nice, but a way more in keeping with ruby's Object Oriented approach is to put all the methods you want access to in a class (as class methods), and then call them from main.rb.

e.g.

file.rb

class MyUtils
    def self.method
        puts "this won't be outputted"
    end
end

and then in main.rb

require "/.file.rb"

and when you want to use your utility methods:

MyUtils.method

I don't think modifying file is good idea - there are could be a lot of files like this one or these files belong to customer and a ton of another reasons.

Ruby is good at metaprogramming so why don't use this feature?

It could be like this.

Create file with fake module and put here the file.

File.open("mfile.rb","w") do |f|
  f.write "module FakeModule
"
  f.write File.open("file.rb").read
  f.write "
end"
end

Then load this file:

require "/.mfile.rb

and accessing to the method:

FakeModule::method
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!