Takezo Shinmen
Takezo Shinmen

Reputation: 49

How can I use a variable in another file on Ruby on Rails?

I'm trying to use my variable in all files of my program. this is an example of what I'm trying to do.

 main.rb
 Class1
 def self.test1
 puts "class 1" if @@debug
  end
 end
 @@ debug = true

 class.test1
 class.test2

 class2.rb
 Class2
 def self.test2
 puts "test2" if @@debug
  end
 end

I really hope it's enough clear for the community, any help would be appreciated, thanks!

Upvotes: 0

Views: 214

Answers (2)

Linuxios
Linuxios

Reputation: 35793

You want a global variable or constant. You could create your own, but Ruby conveniently comes with a builtin $DEBUG global variable. When you specify the -d option to ruby, $DEBUG will be true, and otherwise, false.

If the classes are in multiple files, put this in the file that includes the others:

DEBUG=$DEBUG

And in the other files, use DEBUG for debug, rather than $DEBUG.

Upvotes: 2

sohaibbbhatti
sohaibbbhatti

Reputation: 2682

You can create a getter method to get class_variable

def self.get_debug
  @@debug
end

rails however provides a method called cattr_accessor http://apidock.com/rails/Class/cattr_accessor This will allow you to set and get the class variable outside the class

i.e. Class1.debug = false

Upvotes: 1

Related Questions