Skip to content

Instantly share code, notes, and snippets.

@bradgessler
Created December 21, 2024 08:44
Show Gist options
  • Save bradgessler/620fec6fae7b115f97343db2f5ad218c to your computer and use it in GitHub Desktop.
Save bradgessler/620fec6fae7b115f97343db2f5ad218c to your computer and use it in GitHub Desktop.
Component initializers
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