Created
December 28, 2012 17:12
-
-
Save goshacmd/4399868 to your computer and use it in GitHub Desktop.
Injecting method arguments
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
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 |
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
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