Forum: Ruby Exclude members from YAML conversion?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A40ea9c816d41de88a806fecfaf1afb6?d=identicon&s=25 Christian Kerth (kerthi)
on 2008-11-26 10:24
Hi!

I have the following class:

class user

attr_accessor :userid, :username

def initialize
@userid = ""
@username = ""

@prefix = false
@unprefix = false
end

end

when i convert that with to_yaml, all 4 member variables are translated
into the yaml string. I need to exclude the members @prefix and
@unprefix, they are used just for internal decisions and dosn't need to
be in the yaml string.

how do i do that?
A5b01739148d8795e99582444361a1bc?d=identicon&s=25 Ola Bini (Guest)
on 2008-11-26 10:36
(Received via mailing list)
Christian Kerth wrote:
> @username = ""
> be in the yaml string.
>
> how do i do that?
>

You can override yaml_properties to return only the ones you want to be
in the yaml string.

Cheers

--
 Ola Bini (http://olabini.com)
 JRuby Core Developer
 Developer, ThoughtWorks Studios (http://studios.thoughtworks.com)
 Practical JRuby on Rails (http://apress.com/book/view/9781590598818)

 "Yields falsehood when quined" yields falsehood when quined.
A40ea9c816d41de88a806fecfaf1afb6?d=identicon&s=25 Christian Kerth (kerthi)
on 2008-11-26 10:49
> You can override yaml_properties to return only the ones you want to be
> in the yaml string.

where do i overwrite this method?

in my user object?

can you give an example?

thx
47b1910084592eb77a032bc7d8d1a84e?d=identicon&s=25 Joel VanderWerf (Guest)
on 2008-11-26 18:35
(Received via mailing list)
Christian Kerth wrote:
>> You can override yaml_properties to return only the ones you want to be
>> in the yaml string.
>
> where do i overwrite this method?
>
> in my user object?
>
> can you give an example?
>
> thx

require 'yaml'

class C
   attr_reader :x, :y, :z

   def initialize x, y, z
     @x, @y, @z = x, y, z
   end

   def to_yaml_properties
     super - ["@x"]
   end
end

c = C.new 1, 2, 3
p c.to_yaml_properties
puts c.to_yaml

__END__

Output:

["@y", "@z"]
--- !ruby/object:C
y: 2
z: 3
A40ea9c816d41de88a806fecfaf1afb6?d=identicon&s=25 Christian Kerth (kerthi)
on 2008-11-27 08:01
Joel VanderWerf wrote:
> require 'yaml'
> class C
>    attr_reader :x, :y, :z
>
>    def initialize x, y, z
>      @x, @y, @z = x, y, z
>    end
>    def to_yaml_properties
>      super - ["@x"]
>    end
> end
> c = C.new 1, 2, 3
> p c.to_yaml_properties
> puts c.to_yaml

Thx!
This topic is locked and can not be replied to.