def print title, msg, level
puts hash_for(title, msg, level).to_json
end
alias :info, :print
alias :unknown, :print
하지만 alias
과 alias_method
지원 나타나지 않는 인수를 주입해야합니다.
루비 2.3
def print title, msg, level
puts hash_for(title, msg, level).to_json
end
alias :info, :print
alias :unknown, :print
하지만 alias
과 alias_method
지원 나타나지 않는 인수를 주입해야합니다.
루비 2.3
지금까지 내가 어느 alias
도 alias_method
지원 인수를 알고.
def print(title, msg, level)
puts hash_for(title, msg, level).to_json
end
def info(*args)
print(*args)
end
# More concise...
def unknown(*args); print(*args); end
alias
가 내장이며, 콜론 또는 쉼표 문법적으로 정확하지 않고 사실 alias info print
에서, 매개 변수를 지원하지 않습니다
당신은 다음과 같이 명시 적 방법을 정의 할 수 있습니다. 그러나 alias_method
가 작동해야합니다. 다음은 나를 위해 일했다 :
class G
def print
puts 'print'
end
a = :print
b = :info
alias_method b, a
end
G.new.info
메타 프로그래밍으로 이것을 할 수있다!
class Logger
def self.define_printer(level)
define_singleton_method(level) do |title, msg|
print(title, msg, level)
end
end
def self.print(title, msg, level)
puts hash_for(title, msg, level).to_json
end
define_printer :info
define_printer :unknown
end
Logger.info('foo', 'bar')
# calls print with ["foo", "bar", :info]
편집 : 추가 크레딧으로 일반 버전을 만들었습니다.
class Object
def curry_singleton(new_name, old_name, *curried_args)
define_singleton_method(new_name) do |*moreArgs|
send(old_name, *curried_args.concat(moreArgs))
end
end
end
class Foobar
def self.two_arg_method(arg1, arg2)
p [arg1, arg2]
end
curry_singleton(:one_arg_method, :two_arg_method, 'first argument')
end
Foobar.one_arg_method('second argument')
#=> ["first argument", "second argument"]
예, 좋은 방법 인 것 같습니다. –