如何让模块“扩展”到我的Model类中

时间:2013-03-29 09:42:49

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2

LIB /模块/ sport_time.rb

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

events.rb模型

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

问题:当我尝试创建一个目标时间为“1:15.55”(字符串)的事件时,它不会保存为75.55(浮点数),而是保存为1.0(浮点数) ......所以无论我在课堂上做什么,我都无法正常工作。

我对使用模块非常陌生,所以我很难搞清楚为什么我无法理解我在这里做错了。任何帮助表示感谢,谢谢。

注意:视图的float-to-string转换确实有效。

1 个答案:

答案 0 :(得分:2)

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

确保您的lib目录是自动加载的,或者您可以将mixin放在Mixin :: SportTime模块中的models / mixin目录下