Pedro Morte Rolo Pedro Morte Rolo - 7 months ago 20
Ruby Question

Milliseconds with Rails and Mysql

What is the best way to store Time in milliseconds when using Rails+Mysql?

I am about to use a decimal and composed_of in order to be able to manipulate this value as a Ruby Time. Does anyone have a better idea?!

Thnks,
Pedro

Answer

My approach was to:

open the time class and implement the methods :from_milis and :to_milis :

class Time
  def self.from_milis(milis)
    self.at(milis.to_f/1000)
  end

  def to_milis
    self.to_f*1000
  end
end

migrate the column from timestamp to :decimal,:precision=>17

then, in the AR class in which i am using this column as attribute:

composed_of :ts,
    :class_name=>"Time",
    :mapping=>%w(ts to_milis),
    :constructor=>:from_milis,
    :converter=>:from_milis

I just had gochas when using this attribute in arel queries, where I had to explicitly call to_milis in order to get the intended value in the comparision.