Sha256: 9da63bfcfb8ed1c423d323059722cada91fe205916d4518faf3c72260cd709fb

Contents?: true

Size: 1.78 KB

Versions: 7

Compression:

Stored size: 1.78 KB

Contents

class Time
  class << self
    def extract_from_attributes!(attrs, field, method = :local)
      parse_from_attributes(attrs, field, method).tap do |time|
        attrs.delete_if { |k, v| k.to_s =~ /^#{field}.+/ }
      end unless attrs.blank?
    end

    # 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 = :local)
      attrs = attrs.keys.sort.grep(/^#{field.to_s}\(.+\)$/).map { |k| attrs[k] }
      attrs.any? ? Time.zone.send(method, *attrs) : nil
    end

    def delta(year, month = nil, day = nil)
      from = Time.zone.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

  # Time.now.to_ordinalized_s :long
  # => "February 28th, 2006 21:10"
  def to_ordinalized_s(format = :default)
    format = DATE_FORMATS[format]
    return to_default_s if format.nil?
    strftime(format.gsub(/%d/, '_%d_')).gsub(/_(\d+)_/) { |s| s.to_i.ordinalize }
  end

  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'
end

Version data entries

7 entries across 7 versions & 2 rubygems

Version Path
adva-0.1.4 lib/time_hacks.rb
adva-0.1.3 lib/time_hacks.rb
adva-0.1.2 lib/time_hacks.rb
adva-0.1.1 lib/time_hacks.rb
adva-0.1.0 lib/time_hacks.rb
adva_cms-0.0.1 lib/time_hacks.rb
adva-0.0.1 adva_cms/lib/time_hacks.rb