2012-03-05 2 views
1
class Class 
    def attr_accessor_with_history(attr_name) 
    attr_name = attr_name.to_s 
    # make sure it's a string                               
    attr_reader attr_name 
    # create the attribute's                               

    attr_reader attr_name+"_history" # create bar_history                        

    class_eval %Q{ 

     def #{attr_name}=(val) 
     @#{attr_name+"_history"}=[] 
     @#{attr_name+"_history"}.push(val) 
     @#{attr_name}=val 
     end 
    } 
    end 
end 

class Foo 

    attr_accessor_with_history :bar 
end 

배열에있는 모든 쓰기의 기록을 기록하는 attr 접근자를 만들고 싶지만 문제는 class_eval에 있습니다. 배열은 매번 초기화되므로 이전 값을 보유하지 않습니다.함수를 호출 할 때만 배열을 초기화하는 방법은 무엇입니까?

내가해야 할 변경 사항은 무엇입니까?

+1

사스 코스가 정말 인기가 그 – Sergey

답변

3

사용 ||= :

@#{attr_name+"_history"} ||= [] 
+0

그것은 슈퍼 분명하지 않을 수도 있습니다 정말 멋진,하지만'|| ='첫 번째 줄은 링크가'켜짐 :)'. –

+0

나중에 알아보기 –

관련 문제