Creating a static class variable in ruby

One of the patterns I (over)use in php is having a class with only static variables and static functions. To do this in ruby isn't as straight forward as it could be, so here is how to do it.

class StaticKlass

    # ruby class variables are prefixed with "@@" .
    @@variable = nil

    # If you want to provide getters and setters you cant use the attr_accessor
    # keyword, you have to create them manually. By adding the class name to
    # the method definition, we are indicating that this is a method on the
    # class, not in instances of this class
    def StaticKlass.variable= (x)
        @@variable = x
    end

    # the getter is defined to return the class variable when called
    def StaticKlass.variable
        return @@variable
    end

end

Posted by Lang Sharpe
Tue, 08 Jun 2010 19:00:52 GMT

Leave a comment

Comments