Module: SuperAccessors::Datetime
- Defined in:
- lib/super_accessors/datetime.rb
Instance Method Summary collapse
Instance Method Details
#split_date_hour_min(*attrs) ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/super_accessors/datetime.rb', line 37 def split_date_hour_min(*attrs) opts = { format: "%F", default: lambda { Time.now.change(min: 0) } } if attrs.last.class == Hash custom = attrs.delete_at(-1) opts = opts.merge(custom) end attrs.each do |attr| define_method(attr) do super() || opts[:default].call end define_method("#{attr}_date=") do |date| return unless date.present? date = Date.parse(date.to_s) self.send("#{attr}=", self.send(attr).change(year: date.year, month: date.month, day: date.day)) end define_method("#{attr}_hr=") do |hour| return unless hour.present? self.send("#{attr}=", self.send(attr).change(hour: hour, min: self.send(attr).min)) end define_method("#{attr}_min=") do |min| return unless min.present? self.send("#{attr}=", self.send(attr).change(min: min)) end define_method("#{attr}_date") do self.send(attr).strftime(opts[:format]) end define_method("#{attr}_hr") do self.send(attr).hour end define_method("#{attr}_min") do self.send(attr).min end end end |
#split_date_time(*attrs) ⇒ Object
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/super_accessors/datetime.rb', line 3 def split_date_time(*attrs) opts = { format: "%F", default: lambda { Time.now.change(min: 0) } } if attrs.last.class == Hash custom = attrs.delete_at(-1) opts = opts.merge(custom) end attrs.each do |attr| define_method(attr) do super() || opts[:default].call end define_method("#{attr}_date=") do |date| return unless date.present? date = Date.parse(date.to_s) self.send("#{attr}=", self.send(attr).change(year: date.year, month: date.month, day: date.day)) end define_method("#{attr}_time=") do |time| return unless time.present? time = Time.parse(time.to_s) self.send("#{attr}=", self.send(attr).change(hour: time.hour, min: time.min)) end define_method("#{attr}_date") do self.send(attr).strftime(opts[:format]) end define_method("#{attr}_time") do [self.send(attr).hour.to_s.rjust(2, '0'), self.send(attr).min.to_s.rjust(2, '0')].join(':') end end end |