Last active
November 23, 2017 11:46
-
-
Save oinak/f2ec0cfe56c5b753cebfedc9b8b2dcc6 to your computer and use it in GitHub Desktop.
how to initialize a keyword argument from the superclass (useful for dependency injection)
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
# http://ruby-doc.org/core-2.4.0/doc/syntax/calling_methods_rdoc.html#label-Hash+to+Keyword+Arguments+Conversion | |
class Super | |
attr_reader :shared | |
# ServiceObject style class-level activation method | |
def self.run(**args) | |
new(**args).tap{ |obj| obj.run } | |
end | |
def initialize(shared: 'All subclasses see me', **args) | |
@shared = shared | |
end | |
end | |
class Child < Super | |
def initialize(special: nil, **args) | |
super # this reads **args implicitly! | |
@special = special | |
end | |
def run | |
puts "Shared:#{shared} Special:#{@special}" | |
end | |
end | |
Child.run(special: 2) | |
# Shared:All subclasses see me Special:2 | |
Child.run(shared: "super", special: 2) | |
# Shared:super Special:2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment