2017-02-23 8 views
0

이 코드를 리팩토링 싶습니다Ruby에서 매개 변수와 함께 별칭을 사용하는 방법? 같은 속으로</p> <pre><code>class Logger class << self def info title, msg puts hash_for(title, msg, :info).to_json end def unknown title, msg puts hash_for(title, msg, :unknown).to_json end </code></pre> <p>을 :

def print title, msg, level 
    puts hash_for(title, msg, level).to_json 
end 
alias :info, :print 
alias :unknown, :print 

하지만 aliasalias_method 지원 나타나지 않는 인수를 주입해야합니다.

루비 2.3

답변

0

지금까지 내가 어느 aliasalias_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 
0

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 
1

메타 프로그래밍으로 이것을 할 수있다!

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"] 
+0

예, 좋은 방법 인 것 같습니다. –

관련 문제