Last active
August 29, 2015 14:17
-
-
Save scudelletti/7fb5374c279fd6f732c5 to your computer and use it in GitHub Desktop.
Ruby Class Variable Examples without @@
This file contains hidden or 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
# Ruby Class Variable Examples without @@ | |
# http://www.sitepoint.com/class-variables-a-ruby-gotcha/ | |
class Foo | |
def self.talk | |
puts 'Hey! I\'m talking' | |
end | |
end | |
class Bar | |
def run! | |
Foo.talk | |
end | |
end | |
puts '-' * 150 | |
puts '[Bar]' | |
Bar.new.run! | |
class BarWithInjection | |
@@foo_klass = nil | |
def initialize(foo_klass) | |
@foo_klass = foo_klass | |
end | |
def run! | |
@foo_klass.talk | |
end | |
end | |
puts '-' * 150 | |
puts '[BarWithInjection]' | |
BarWithInjection.new(Foo).run! | |
class BarWithExternalInjection | |
class << self | |
attr_accessor :foo_klass | |
end | |
def self.set_foo_class(klass) | |
@foo_klass = klass | |
end | |
def self.run! | |
@foo_klass.talk | |
end | |
def instance_run! | |
self.class.foo_klass.talk | |
end | |
end | |
puts '-' * 150 | |
puts '[BarWithExternalInjection]' | |
BarWithExternalInjection.set_foo_class(Foo) | |
BarWithExternalInjection.run! | |
BarWithExternalInjection.foo_klass | |
puts '.' * 150 | |
puts '[BarWithExternalInjection] INSTANCE' | |
BarWithExternalInjection.new.instance_run! | |
puts '-' * 150 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment