How to easily set class-level defaults

08 Jun 2013

I was reading “Eloquent Ruby” by Russ Olsen earlier this week, and got really excited when I came across a neat little way to create default values for classes.

Russ uses the example of a Document class:

class Document

@default_font = :times

class << self
attr_accessor :default_font
end

# Rest of the class omitted...
end

These few lines of code get you both a getter and setter for your newly created “default_font” class method.

I’m not sure why that was so exciting to me ha, but I figured it might excite someone else out there just the same.

Enjoy!