1

created_at のメソッドを追加するモンキー パッチを作成しようとしています。

date_time_extras.rb ファイルを作成し、lib次の内容でディレクトリに配置しました。

class DateTime
  def beginning_of_hour
    change(:min => 0)
  end
end

私が行うコンソールから:

record.created_at.beginning_of_hour

しかし、これによりメソッドの欠落エラーが発生します。created_at は日時ではないようです。DateTime.new.beginning_of_hour動作し、record.created_at.class利回りが得られるためActiveSupport::TimeWithZoneです。

では、created_at 型の日付のモンキー パッチを作成するにはどうすればよいでしょうか。

Rails バージョン 3.0.10 を使用しています。

アップデート

また試した

module ActiveSupport
  class TimeWithZone
    def beginning_of_hour
      change(:min => 0)
    end
  end
end

無駄に

4

1 に答える 1

0

で宣言してみましたclass Timeか?

class DateTime
  def beginning_of_hour
    change(:min => 0)
  end
end

TimeWithZoneTime時間オブジェクトをnotに委任しているように見えますDateTime

TimeWithZoneオブジェクトだけではないので、次の@timeようなことをする必要があります

module ActiveSupport
  class TimeWithZone
    def beginning_of_hour
      self.time.change(:min => 0)
    end
  end
end

しかし、私はそのコードについて100%確信していません。

于 2012-05-09T01:58:47.377 に答える