Reputation: 118
module SportTime
def to_race_time(secs)
m = (secs/60).floor
s = (secs - (m*60))
t = sprintf("%02d:%.2f\n",m,s)
return t
end
def time_to_float(tim)
dirty = tim.to_s
min, sec = dirty.split(":")
seconds = (min.to_i * 60) + sec.to_f
seconds.round(4)
end
end
class Event
extend SportTime
before_save :sporty_save
private
def sporty_save
self.goal_time = self.class.time_to_float(goal_time)
end
end
class Event < ActiveRecord::Base
validates_presence_of :course, :goal_time, :race_length, :user_id
attr_accessible :course, :goal_time, :race_length, :user_id
belongs_to :user
end
Problem: When I try to create an Event with a goal_time of "1:15.55" (string), instead of being saved as 75.55 (float), it's being saved as 1.0 (float)...so whatever I'm doing with the class mixin clearly isn't working.
I'm pretty new to working with modules, so I'm having a tough time figuring out why I can't get it to I'm doing wrong here. Any help appreciated, thanks.
Note: the float-to-string conversion for the view does work.
Upvotes: 0
Views: 113
Reputation: 485
module SportTime
extend ActiveSupport::Concern
included do
before_save :sporty_save
end
private
def sporty_save
self.goal_time = time_to_float(goal_time)
end
def to_race_time(secs)
m = (secs/60).floor
s = (secs - (m*60))
sprintf("%02d:%.2f\n",m,s)
end
def time_to_float(tim)
dirty = tim.to_s
min, sec = dirty.split(":")
seconds = (min.to_i * 60) + sec.to_f
seconds.round(4)
end
end
class Event < ActiveRecord::Base
include SportTime
validates_presence_of :course, :goal_time, :race_length, :user_id
attr_accessible :course, :goal_time, :race_length, :user_id
belongs_to :user
end
And make sure your lib directory is autoloaded or you can place your mixins under models/mixin directory in Mixin::SportTime module
Upvotes: 2