Skip to content

Instantly share code, notes, and snippets.

@oinak
Last active November 23, 2017 11:46
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 oinak/f2ec0cfe56c5b753cebfedc9b8b2dcc6 to your computer and use it in GitHub Desktop.
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)
# 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