[Nitro] Concerns over Og mandating the form of initialize

George Moschovitis george.moschovitis at gmail.com
Thu Apr 14 14:11:10 EDT 2005


Sorry for that, let me try again...

class Foo
  prop_accessor :x, :y # save those attributes
  attr_accessor :calc # don't save this attribute can be calculated from x,y

  def initalize(x, y)
    @x, @y = x, y
    
    # i want the mail sent only when creating the object
    mail('gm at navel.gr', 'Hey, a new foo was created')

    # lets create a variable from x, y
    # as it can be calculated there is no need to save this

    @calc = @x * @y
end

obviously you dont want to call the initialize method every time the
object is read (== deserialized) from the database. But you need to to
generate the @calc variable after reading to have a valid Foo object.
Og needs some help here. Og cannot decide alone how to skip the mail
and just generate calc. So we give Og a hint:

class Foo
  ...

  post(:on => :og_read) { |this| this.calc = this.x * this.y }
  # or more efficiently:
  post "@calc = @x * @y", :on => :og_read
end

with this tip Og does the following when reading the object:

f = Foo.allocate
f.og_read 

where Foo#og_read does the following:

def og_read(res)
  @x = res['x']
  @y = res['y']
  @calc = @x * @y
end

please note that Og automatically generates og_read. So you really
only need to add one line of code to make Og handle your class. Plus
you are free to design the initialize method as you like. Even better
I suggest to do some refactoring:

class Foo
  def initialize(x,y)
    @x, @y = x, y
  end

  def do_calc
    @calc = @x * @y
  end

  post :do_calc, :on => [ :initialize, :og_read ]
end

please note, this uses the AOP features in 0.16.0   

-g.

-- 
http://nitro.rubyforge.org
http://www.joy.gr




More information about the Nitro-general mailing list