The beginning steps to writing a new class usually involve writing a quick
def initialize method. The purpose of these type of methods is to
setup any dependencies or configurations necessary for the object to fulfill its
responsibility. With instance variables, a common paradigm is to use an attr_reader
or attr_writer to read/write values. However, these methods specifically work
off of instance variables.
The difference between instance variables and class variables
attr_ is basically a shortcut for getter and setter methods. For
example, if you have the following initializer method, and wanted to access the
@element in a private method, you might do something
This approach works because you reference the set instance variable @element. However, for class methods you don’t have access to instance level variables so something like the following won’t work:
The reason the instance variable isn’t available is that the context that the above is ran in is the class context. In other words it runs directly off the class like a method while instances of that class represent an object.
For SiteBuilder.new(element), we are creating a new object instance of the SiteBuilder class. The element becomes part of its properties or what describes its data and features.
For SiteBuilder.format(element), we are calling a method that works off of whatever the input is. It isn’t a new object but rather a way to perform an operation on something that doesn’t need an object.
Using an attr_accessor method with class level methods
Still want to have the benefits of attr_reader, attr_writer, and attr_accessor? We can implement another approach that allows the usage of these instance variables in a class level context. Basically what it does is create an instance variable in the class context to be used elsewhere.comments powered by Disqus