Skip to content

Instantly share code, notes, and snippets.

@scudelletti
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scudelletti/7fb5374c279fd6f732c5 to your computer and use it in GitHub Desktop.
Save scudelletti/7fb5374c279fd6f732c5 to your computer and use it in GitHub Desktop.
Ruby Class Variable Examples without @@
# 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