Require file without executing code?

前端 未结 3 735
走了就别回头了
走了就别回头了 2021-02-07 06:22

Here I have two files:

file.rb

def method
  puts \"This won\'t be outputted.\"
end

puts \"This will be outputted.\"

main.rb

<
3条回答
  •  被撕碎了的回忆
    2021-02-07 07:03

    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
    

提交回复
热议问题