Created
December 21, 2024 08:44
-
-
Save bradgessler/620fec6fae7b115f97343db2f5ad218c to your computer and use it in GitHub Desktop.
Component initializers
This file contains 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 Component | |
attr_writer :post | |
def initialize(session:, fun: "bags", deeze:) | |
@session = session | |
@fun = fun # Make sure we assign this, otherwise @fun would be nil | |
@deeze = deeze | |
end | |
end | |
# Some globals (simulating a Rails controller context, etc.) | |
@post = "This is wonderful!" | |
@session = {} | |
@deeze = "🥜!" | |
def extract_initialize_values(klass, initializer: :initialize) | |
klass | |
.instance_method(initializer) | |
.parameters | |
.each_with_object Hash.new do |param, hash| | |
case param | |
in :keyreq, name | |
hash[name] = instance_variable_get("@#{name}") if instance_variable_defined?("@#{name}") | |
in :key, name | |
hash[name] = instance_variable_get("@#{name}") if instance_variable_defined?("@#{name}") | |
else | |
puts "No match for #{param}" | |
next | |
end | |
end | |
end | |
def assign_attr_writers(instance) | |
instance.tap do |instance| | |
instance.instance_variables.each do |variable| | |
attr_writer_name = "#{variable[1..-1]}=" | |
if instance.respond_to?(attr_writer_name) | |
instance.send( | |
attr_writer_name, | |
instance.instance_variable_get(variable) | |
) | |
end | |
end | |
end | |
end | |
def initialize_keyword_arguments(klass) | |
klass.new **extract_initialize_values(klass) | |
end | |
def component(klass) | |
assign_attr_writers initialize_keyword_arguments Component | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment