Created
November 19, 2012 19:31
-
-
Save sdeming/4113126 to your computer and use it in GitHub Desktop.
Totally Contrived Episode #1 - class << self
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
class Foo | |
class << self | |
attr_accessor :a, :b | |
end | |
def self.register(args = {}) | |
args.each do |k,v| | |
self.send(:"#{k}=", v) | |
end | |
end | |
def self.moo | |
a * b | |
end | |
end | |
class FooLish < Foo | |
register :a => 7, :b => 6 | |
end | |
class FooNiture < Foo | |
register :a => 1, :b => 2 | |
end | |
puts FooLish.moo | |
puts FooNiture.moo | |
jmazzi
commented
Nov 19, 2012
Updated it to be a little more real-worldish... Not much, just a little.
class Foo
def self.a
6
end
def self.b
7
end
def self.moo
a + b
end
end
class Boo < Foo
def self.b
8
end
end
p Foo.moo #=> 13
p Boo.moo #=> 14
class Foo
def self.register(config = {})
config.each do |k,v|
define_singleton_method k do
v
end
end
end
register :a => 1, :b => 2
def self.moo
a * b
end
end
class Boo < Foo
register :b => 3
end
p Foo.moo
p Boo.moo
p Foo.moo
It's silly that you can't edit gist comments. The output of that is:
2
3
2
module StrictlyConfigurable
def register(config = {})
config.each do |k,v|
define_singleton_method k do
v
end
end
end
end
class Foo
extend StrictlyConfigurable
register :a => 1, :b => 2
def self.moo
a * b
end
end
class Boo < Foo
register :b => 3
end
p Foo.moo
p Boo.moo
p Foo.moo
👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment