Exclude members from YAML conversion?


#1

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?


#2

Christian K. 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 B. (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.


#3

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


#4

Christian K. 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


#5

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!