I dont understand what an instance variable inside a class method does. Below code makes no sense to me. How can a class method manipulate an instance variable? I can call a class method without even having an instance.
return @schema if @schema
DB.table_info(table) do |row|
@schema[row['name']] = row['type']
In short, these instance variables belong to the class, not the instances of that class.
To understand it, you need to know more about Ruby.
In Ruby, all the classes are just objects of type
String.class #=> Class Array.class #=> Class Class.class #=> Class
And you can define anonymous classes by instantiating
foo = Class.new do # Here you can define methods end foo.new #=> an instance of an anonymous class
Because classes are objects, they can have instance variables too.
There are 4 keywords that triggers scope switching:
do (for blocks). Here I only show the
# in the scope of main class Foo # in the scope of Foo def self.bar # still in the scope of Foo end # in the scope of Foo def bar # in the scope of an instance of Foo end # back to the scope of Foo again end # back to the scope of main
The instance variables defined in a scope belongs to the current object (a.k.a.
self) of that scope. In the previous example, if you define a instance variable in the scope of
Foo, that instance variable belongs to the
self of that scope, which is the class