We all know that class variables such as @@ are dangerous to use due to their leaky inheritance.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Presentaion < Document | |
@@default_font = :ariel | |
def self.default_font=(font) | |
@@default_font=(font) | |
end | |
def default_font | |
@@default_font | |
end | |
end | |
class Resume < Document | |
@@default_font = :nimbus | |
def self.default_font=(font) | |
@@default_font=(font) | |
end | |
def default_font | |
@@default_font | |
end | |
end | |
class Document | |
@@default_font = :times ##LEAKY INTHERITANCE HERE | |
end | |
require 'document' | |
require 'resume' # Rewrite class variable | |
require 'presentation' # Rewrite class viable | |
##THE FIX | |
# As an alternative we can use... | |
# 1. Use class variables with this in mind | |
# 2. Use CONSTANTS | |
# 3. Open up the Singleton Class | |
class Presentaion < Document | |
@default_font = :ariel | |
class << self | |
attr_accessor :default_font | |
end | |
end | |
class Resume < Document | |
@default_font = :nimbus | |
class << self | |
attr_accessor :default_font | |
end | |
end | |
class Document | |
@default_font = :times | |
class << self | |
attr_accessor :default_font | |
end | |
end | |
<script src="https://gist.github.com/surgentt/9464842.js"></script>class Presentaion < Document
WHAT IS GOING ON HERE
The class << self syntax opens up a classes singleton class.
This allows you to specialize the behavior of methods called on that specific object.
http://stackoverflow.com/questions/2505067/class-self-idiom-in-ruby
Object
^
|
<Singleton Class>
^
|
Instance
Singleton Method is a method that is defined for exactly one object instance.
The <Singleton Class> is only invoked when it is filled with something.
- An example of this is a method on an instance variable.
|
No comments:
Post a Comment