Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require file without executing code?

Tags:

ruby

require

Here I have two files:

file.rb

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

puts "This will be outputted."

main.rb

require "./file"

When running main.rb it will load all the code inside file.rb so I will get "This will be outputted." on the screen.

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

Cause I want to load all the methods (in modules and classes too) without having to execute code outside these scopes.

like image 864
never_had_a_name Avatar asked Sep 19 '10 10:09

never_had_a_name


2 Answers

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"
like image 199
sepp2k Avatar answered Sep 30 '22 00:09

sepp2k


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
like image 22
stephenr Avatar answered Sep 30 '22 00:09

stephenr