The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
ActiveRecord serialize only saves data

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Paul Gross

Posts: 152
Nickname: pgross
Registered: Sep, 2007

Paul Gross is a software developer for ThoughtWorks.
ActiveRecord serialize only saves data Posted: Feb 20, 2008 8:31 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Paul Gross.
Original Post: ActiveRecord serialize only saves data
Feed Title: Paul Gross's Blog - Home
Feed URL: http://feeds.feedburner.com/pgrs
Feed Description: Posts mainly about ruby on rails.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Paul Gross
Latest Posts From Paul Gross's Blog - Home

Advertisement

We ran into an interesting gotcha on our project the other day. We use serialize on ActiveRecord to save ruby objects to the database. This is described in Jay Fields Thoughts: Rails: ActiveRecord Serialize method.

Serialize uses YAML.dump and YAML.load to serialize/deserialize objects to strings. These methods only deal with the data of an object, not the methods. The objects we serialized used metaprogramming to dynamically define methods. When they were loaded from the database, they no longer had the new methods.

Here is a contrived example. The Foo class creates a foo method in the initialize:


class Foo
  def initialize
    class << self
      define_method :foo, lambda { 10 }
    end
  end
end

>> Foo.new.foo
=> 10

A dump of the Foo class has no knowledge of this foo method:


>> require 'yaml'
>> YAML.dump(Foo.new)
=> "--- !ruby/object:Foo {}\n\n" 

Therefore, the loaded version of Foo will not have the foo method:


>> YAML.load(YAML.dump(Foo.new)).foo
NoMethodError: undefined method `foo' for #<Foo:0xb7985af0>
        from (irb):16

In our case, we changed our code to store only the data from the domain object in the database (in columns). We recreate the domain object from these columns when we need it.

Read: ActiveRecord serialize only saves data

Topic: Rails App Without Tests = Guaranteed Fail Previous Topic   Next Topic Topic: Return to Generating a Unique Number

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use