Skip to content

Instantly share code, notes, and snippets.

@goshacmd
Created December 28, 2012 17:12
Show Gist options
  • Save goshacmd/4399868 to your computer and use it in GitHub Desktop.
Save goshacmd/4399868 to your computer and use it in GitHub Desktop.
Injecting method arguments
i = Injector.new first: 'First Name', last: 'Last Name', power: 2
def full_name(first, last)
"#{first} #{last}"
end
def random_to_power(power)
4 ** power
end
p i.call method(:full_name) # => "First Name Last Name"
p i.call method(:random_to_power) # => 16
class Injector
def initialize(mappings)
@mappings = mappings
end
def params(meth)
meth.parameters.map { |(type, name)| name }
end
def args(meth)
[].tap do |a|
params(meth).each do |p|
a << @mappings[p]
end
end
end
def call(meth)
meth.call *args(meth)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment