Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.ruby
Re: Question on IO objects, initialize, and yaml
Eric Hodel
12/11/2006 1:24:00 AM
On Dec 10, 2006, at 12:19 , Mark Noworolski wrote:
> Say I have a class with pseudo code as follows:
> class Test
> def initialize
> @a=1
> @b=File.open("file+Time.now or similar")
> end
> end
>
> Now, imagine that I use this class for a while and then I want to
> dump it to
> a YAML file.
>
> When I restart my code, I want it to read in stuff from the YAML
> file (if it
> exists) and use that as a starting point to work from (basically, I am
> saving state in the yaml file). You'll note that I cannot just do
> this as
> is, because reading in from YAML does not initialize the class, so
> @b would
> not be initialized correctly on restart.
Ruby and YAML provide hooks to cause things to happen when you load
from Marshal or YAML. I think #initialize_copy gets called for
Marshal, I don't know the YAML ones, but they should be easy to find.
> I'd like to just initialize the thing, then read in the YAML file to
> overwrite the state with the saved values. Is there some extremely
> obvious
> ruby way to do this or something equivalent?
Don't do this, use the built-in hooks, that's what they're for.
--
Eric Hodel - drbrain@segment7.net -
http://blog.se...
I LIT YOUR GEM ON FIRE!
1 Answer
Mauricio Fernández
12/12/2006 12:08:00 AM
0
On Mon, Dec 11, 2006 at 02:43:22PM +0900, Mark Noworolski wrote:
> On 12/10/06, Eric Hodel <drbrain@segment7.net> wrote:
> >
> >Ruby and YAML provide hooks to cause things to happen when you load
> >from Marshal or YAML. I think #initialize_copy gets called for
> >Marshal, I don't know the YAML ones, but they should be easy to find.
> >
> I _want_ to use a built-in hook (the ruby way, if you will), if I can figure
> out which one and how to use it.
[...]
> Now, I've experimented with initialize_copy on this code and your
> recommendation, and I cannot get it to do what I want.
>
> Anybody got any other suggestions, or a concrete example for me?
> mark
require 'yaml'
class Foo
def initialize
@foo = 1
@bar = 2
end
def yaml_initialize(tag, val)
end
end
foo = Foo.new
foo # => #<Foo:0xa7dfe614 @bar=2, @foo=1>
YAML.load(YAML.dump(foo)) # => #<Foo:0xa7dfa6e0>
class Foo
def yaml_initialize(tag, val) # !> method redefined; discarding old yaml_initialize
@foo, @bar = val.values_at("foo", "bar")
end
end
YAML.load(YAML.dump(foo)) # => #<Foo:0xa7ddcfc8 @bar=2, @foo=1>
--
Mauricio Fernandez -
http://eige...
- singular Ruby
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
Re: Question on IO objects, initialize, and yaml
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password