Advertisement
Guest User

Untitled

a guest
Jul 27th, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. class Completion < ActiveRecord::Base
  2. belongs_to :task
  3. belongs_to :user
  4.  
  5. def time_spent_text
  6. ChronicDuration.output time_spent
  7. end
  8.  
  9. def time_spent_text= text
  10. self.time_spent = ChronicDuration.parse text
  11. logger.debug "time_spent: '#{self.time_spent_text}' for text '#{text}'"
  12. end
  13.  
  14. end
  15.  
  16. class DurationType < ActiveRecord::Type::String
  17. def cast(value)
  18. return value if value.blank? || value.is_a?(ActiveSupport::Duration)
  19.  
  20. ActiveSupport::Duration.parse(value)
  21. end
  22.  
  23. def serialize(duration)
  24. duration ? duration.iso8601 : nil
  25. end
  26. end
  27.  
  28. ActiveRecord::Type.register(:duration, DurationType)
  29.  
  30. create_table :somethings do |t|
  31. t.duration :string
  32. end
  33.  
  34. class Something < ApplicationRecord
  35. attribute :duration, :duration
  36. end
  37.  
  38. something = Something.new
  39. something.duration = 1.year # 1 year
  40. something.duration = nil
  41. something.duration = "P2M3D" # 2 months, 3 days (ISO8601 string)
  42. Time.now + something.duration # calculation is always correct
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement