2010-11-30 5 views
5

개체를 serialize/deserialize하는 사용자 지정 메서드를 정의해야합니다. 나는 다음과 같은 것을하고 싶다.사용자 지정 to_yaml 및 domain_type

class Person 
    def to_yaml_type 
    "!example.com,2010-11-30/Person" 
    end 

    def to_yaml 
    "string representing person" 
    end 

    def from_yaml(yaml) 
    Person.load_from(yaml) 
    end 
end 

직렬화/직렬화를 선언하는 올바른 방법은 무엇입니까? 당신은 단지 전용 속성의 하위 집합을 직렬화하려면

답변

5

확인, 여기에 내가

class Person 

    def to_yaml_type 
    "!example.com,2010-11-30/person" 
    end 

    def to_yaml(opts = {}) 
    YAML.quick_emit(nil, opts) { |out| 
     out.scalar(taguri, to_string_representation, :plain) 
    } 
    end 

    def to_string_representation 
    ... 
    end 

    def Person.from_string_representation(string_representation) 
    ... # returns a Person 
    end 
end 

YAML::add_domain_type("example.com,2010-11-30", "person") do |type, val| 
    Person.from_string_representation(val) 
end 
4

해낸거야, 모든 이들, 당신은 to_yaml_properties를 사용할 수 있습니다.

+1

참고로, 이것은 '% w [@foo @bar]'와 같은 인스턴스 변수 이름 목록이어야합니다. – tadman

관련 문제