Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Completion < ActiveRecord::Base
- belongs_to :task
- belongs_to :user
- def time_spent_text
- ChronicDuration.output time_spent
- end
- def time_spent_text= text
- self.time_spent = ChronicDuration.parse text
- logger.debug "time_spent: '#{self.time_spent_text}' for text '#{text}'"
- end
- end
- class DurationType < ActiveRecord::Type::String
- def cast(value)
- return value if value.blank? || value.is_a?(ActiveSupport::Duration)
- ActiveSupport::Duration.parse(value)
- end
- def serialize(duration)
- duration ? duration.iso8601 : nil
- end
- end
- ActiveRecord::Type.register(:duration, DurationType)
- create_table :somethings do |t|
- t.duration :string
- end
- class Something < ApplicationRecord
- attribute :duration, :duration
- end
- something = Something.new
- something.duration = 1.year # 1 year
- something.duration = nil
- something.duration = "P2M3D" # 2 months, 3 days (ISO8601 string)
- Time.now + something.duration # calculation is always correct
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement