Search code examples
ruby

How do I access class variable?


class TestController < ApplicationController

  def test
    @goodbay = TestClass.varible
  end
end

class TestClass
  @@varible = "var"
end

and i get error

undefined method 'varible' for TestClass:Class 

on the line @goodbay = TestClass.varible

What is wrong?


Solution

  • In Ruby, reading and writing to @instance variables (and @@class variables) of an object must be done through a method on that object. For example:

    class TestClass
      @@variable = "var"
      def self.variable
        # Return the value of this variable
        @@variable
      end
    end
    
    p TestClass.variable #=> "var"
    

    Ruby has some built-in methods to create simple accessor methods for you. If you will use an instance variable on the class (instead of a class variable):

    class TestClass
      @variable = "var"
      class << self
        attr_accessor :variable
      end
    end
    

    Ruby on Rails offers a convenience method specifically for class variables:

    class TestClass
      mattr_accessor :variable
    end