Skip to content

Instantly share code, notes, and snippets.

@mrsimo
Created January 15, 2013 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrsimo/4537583 to your computer and use it in GitHub Desktop.
Save mrsimo/4537583 to your computer and use it in GitHub Desktop.
This used to work in ruby 1.8 In ruby 1.9 it creates an endless recursion. Where's my mistake?
class RestObject
(...)
##
# To be able to serialize objects they can't have Proc's, and @response/@request
# have them. So we remove them before actually doing the to_yaml.
def to_yaml(*args)
old_values = @response, @request
@response, @request = nil, nil
begin
super(*args)
ensure
@response, @request = old_values
end
end
end
@txus
Copy link

txus commented Jan 15, 2013

class Obj
  def initialize
    @proc1 = -> { 3 }
    @foo = 'bar'
    @bar = 'baz'
  end

  def serializable_dup
    dup.tap do |duplicate|
      duplicate.instance_variables.each { |iv|
        value = duplicate.instance_variable_get(iv)
        duplicate.instance_variable_set(iv, nil) if value.is_a?(Proc)
      }
    end
  end
end

p Marshal.dump(Obj.new.serializable_dup)

@mrsimo
Copy link
Author

mrsimo commented Jan 15, 2013

Well, that would work for Marshal, but in this case I think I really need to have YAML serialization working.

Some background... I have an AR::Base class which:

serialize :current_params, Hash

It's not nice, but works very well for what I need. This is not something I can easily change the serializing to Marshaling because there's lots of entries already and are actually kind of jobs that are processed in the meantime.

I believe I'm fucking up something when redefining to_yaml :S

@diasjorge
Copy link

In ruby you can specify what gets serialized in yaml like this:

def to_yaml_properties
  [:@id]
end

another example

def to_yaml_properties
  instance_variables - [:@proxy, :@identity]
end

Maybe this can help?

@mrsimo
Copy link
Author

mrsimo commented Jan 15, 2013

You're a star Jorge. That works wonderfully.

With all my google searches I couldn't find that anywhere. Guess I was searching for the wrong thing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment