public
Fork of halorgium/mephisto
Description: A mirror of the mephisto code-base
Homepage: http://mephistoblog.com/
Clone URL: git://github.com/technoweenie/mephisto.git
Click here to lend your support to: mephisto and make a donation at www.pledgie.com !
mephisto / config / initializers / time_hacks.rb
100644 54 lines (49 sloc) 1.732 kb
1
2
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# Time.now.to_ordinalized_s :long
# => "February 28th, 2006 21:10"
module ActiveSupport::CoreExtensions::Time::Conversions
  def to_ordinalized_s(format = :default)
    format = ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS[format]
    return to_default_s if format.nil?
    strftime(format.gsub(/%d/, '_%d_')).gsub(/_(\d+)_/) { |s| s.to_i.ordinalize }
  end
end
 
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.update \
  :standard => '%B %d, %Y @ %I:%M %p',
  :stub => '%B %d',
  :time_only => '%I:%M %p',
  :plain => '%B %d %I:%M %p',
  :mdy => '%B %d, %Y',
  :my => '%B %Y'
 
class Time
  class << self
    # Used for getting multifield attributes like those generated by a
    # select_datetime into a new Time object. For example if you have
    # following <tt>params={:meetup=>{:"time(1i)=>..."}}</tt> just do
    # following:
    #
    # <tt>Time.parse_from_attributes(params[:meetup], :time)</tt>
    def parse_from_attributes(attrs, field, method=:gm)
      attrs = attrs.keys.sort.grep(/^#{field.to_s}\(.+\)$/).map { |k| attrs[k] }
      attrs.any? ? Time.send(method, *attrs) : nil
    end
 
    def delta(year, month = nil, day = nil)
      from = Time.local(year, month || 1, day || 1)
      
      to =
        if !day.blank?
          from.advance :days => 1
        elsif !month.blank?
          from.advance :months => 1
        else
          from.advance :years => 1
        end
      return [from.midnight, to.midnight-1]
    end
  end
 
  def to_delta(delta_type = :day)
    case delta_type
      when :year then self.class.delta(year)
      when :month then self.class.delta(year, month)
      else self.class.delta(year, month, day)
    end
  end
end