class Object

Constants

URLIZE_EXTENSIONS
URLIZE_REMOVE
URLIZE_SEPARATORS

“…Only alphanumerics [0-9a-zA-Z], the special characters ”$-_.+!*'(),“ [not including the quotes - ed], and reserved characters used for their reserved purposes may be used unencoded within a URL.”

Public Class Methods

from_date_numeric(aString) click to toggle source

create a new Time from eg. “20081231”

# File lib/buzztools/extend_time.rb, line 88
def self.from_date_numeric(aString)
        return nil unless aString
        local(aString[0,4].to_i,aString[4,2].to_i,aString[6,2].to_i)
end
from_file(aFilename) click to toggle source
# File lib/buzztools/extend_string.rb, line 206
def self.from_file(aFilename)
        File.open(aFilename, "rb") { |f| f.read }
end
from_ms(aMilliseconds) click to toggle source

creates a Time object from an integer date stamp (milliseconds since 1970) compatible with Javascript It will be in local timezone

# File lib/buzztools/extend_time.rb, line 116
def self.from_ms(aMilliseconds)
        at(aMilliseconds/1000.0)
end
from_zoneless_ms(aTimems) click to toggle source

Useful for building a UTC/zoneless Time from ms since the epoch For Freewheeler : eg. Time.from_zoneless_ms(packet.timems).to_zone(packet.tzm/60)

# File lib/buzztools/extend_time.rb, line 141
def self.from_zoneless_ms(aTimems)
        from_ms(aTimems).utc
end
local_offset() click to toggle source

offset of local machine from UTC, in seconds eg +9.hours

# File lib/buzztools/extend_time.rb, line 56
def self.local_offset
        local(2000).utc_offset
end
max(a, b) click to toggle source
# File lib/buzztools/extend_more.rb, line 31
def self.max(a, b)
        a > b ? a : b
end
min(a, b) click to toggle source
# File lib/buzztools/extend_more.rb, line 35
def self.min(a, b)
        a < b ? a : b
end
random_word(min=4,max=8) click to toggle source
# File lib/buzztools/extend_string.rb, line 3
def self.random_word(min=4,max=8)
        len = min + rand(max-min+1)
        result = ' '*len
        (len-1).downto(0) {|i| result[i] = (?a.ord + rand(?z.ord-?a.ord+1)).chr}
        return result
end

Public Instance Methods

at_beginning_of_day()
Alias for: beginning_of_day
at_midnight()
Alias for: beginning_of_day
beginning_of_day() click to toggle source
# File lib/buzztools/extend_time.rb, line 45
def beginning_of_day
        (self - self.seconds_since_midnight).change(:usec => 0)
end
begins_with?(aString) click to toggle source
# File lib/buzztools/extend_string.rb, line 102
def begins_with?(aString)
        self[0,aString.length]==aString
end
bite(aValue=$/) click to toggle source
# File lib/buzztools/extend_string.rb, line 72
def bite(aValue=$/)
        bite!(aValue,self.dup)
end
bite!(aValue=$/,aString=self) click to toggle source

Like chomp! but operates on the leading characters instead. The aString parameter would not normally be used.

# File lib/buzztools/extend_string.rb, line 57
def bite!(aValue=$/,aString=self)
        if aValue.is_a? String
                if aString[0,aValue.length] == aValue
                        aString[0,aValue.length] = ''
                        return aString
                else
                        return aString
                end
        elsif aValue.is_a? Regexp
                return aString.sub!(aValue,'') if aString.index(aValue)==0
        else
                return aString
        end
end
change(options) click to toggle source
# File lib/buzztools/extend_time.rb, line 4
    def change(options)
            # ::Time.send(
            #    self.utc? ? :utc : :local,
            #    options[:year]  || self.year,
            #    options[:month] || self.month,
            #    options[:day]   || self.day,
            #    options[:hour]  || self.hour,
            #    options[:min]   || (options[:hour] ? 0 : self.min),
            #    options[:sec]   || ((options[:hour] || options[:min]) ? 0 : self.sec),
            #    options[:usec]  || ((options[:hour] || options[:min] || options[:sec]) ? 0 : self.usec)
            # )

            new_year  = options.fetch(:year, year)
new_month = options.fetch(:month, month)
new_day   = options.fetch(:day, day)
new_hour  = options.fetch(:hour, hour)
new_min   = options.fetch(:min, options[:hour] ? 0 : min)
new_sec   = options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec)

if new_nsec = options[:nsec]
  raise ArgumentError, "Can't change both :nsec and :usec at the same time: #{options.inspect}" if options[:usec]
  new_usec = Rational(new_nsec, 1000)
else
  new_usec  = options.fetch(:usec, (options[:hour] || options[:min] || options[:sec]) ? 0 : Rational(nsec, 1000))
end

if utc?
  ::Time.utc(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec)
elsif zone
  ::Time.local(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec)
else
  raise ArgumentError, 'argument out of range' if new_usec > 999999
  ::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec + (new_usec.to_r / 1000000), utc_offset)
end

    end
date() click to toggle source
# File lib/buzztools/extend_time.rb, line 60
def date
        self.at_beginning_of_day
end
date_numeric() click to toggle source
# File lib/buzztools/extend_time.rb, line 79
def date_numeric
        self.strftime('%Y%m%d')
end
datetime_numeric() click to toggle source
# File lib/buzztools/extend_time.rb, line 97
def datetime_numeric
        self.strftime('%Y%m%d-%H%M%S')
end
day_end() click to toggle source

the last microsecond of the day

# File lib/buzztools/extend_time.rb, line 75
def day_end
        self.at_beginning_of_day + 86399.999999
end
day_number() click to toggle source

index number of this day, from Time.at(0) + utc_offset

# File lib/buzztools/extend_time.rb, line 65
def day_number
        (self.to_i+self.utc_offset) / 86400
end
day_number_utc() click to toggle source

index number of this utc day

# File lib/buzztools/extend_time.rb, line 70
def day_number_utc
        self.to_i / 86400
end
deprefix(aValue=$/) click to toggle source
# File lib/buzztools/extend_string.rb, line 85
def deprefix(aValue=$/)
        deprefix!(aValue,self.dup)
end
deprefix!(aPrefix=$/,aString=self) click to toggle source
# File lib/buzztools/extend_string.rb, line 76
def deprefix!(aPrefix=$/,aString=self)
        if aString[0,aPrefix.length] == aPrefix
                aString[0,aPrefix.length] = ''
                return aString
        else
                return aString
        end
end
desuffix(aValue=$/) click to toggle source
# File lib/buzztools/extend_string.rb, line 98
def desuffix(aValue=$/)
        desuffix!(aValue,self.dup)
end
desuffix!(aSuffix=$/,aString=self) click to toggle source
# File lib/buzztools/extend_string.rb, line 89
def desuffix!(aSuffix=$/,aString=self)
        if aString[-aSuffix.length,aSuffix.length] == aSuffix
                aString[-aSuffix.length,aSuffix.length] = ''
                return aString
        else
                return aString
        end
end
ends_with?(aString) click to toggle source
# File lib/buzztools/extend_string.rb, line 106
def ends_with?(aString)
        self[-aString.length,aString.length]==aString
end
ensure_prefix(aValue=$/) click to toggle source
# File lib/buzztools/extend_string.rb, line 115
def ensure_prefix(aValue=$/)
        ensure_prefix!(aValue,self.dup)
end
ensure_prefix!(aPrefix=$/,aString=self) click to toggle source
# File lib/buzztools/extend_string.rb, line 110
def ensure_prefix!(aPrefix=$/,aString=self)
        aString[0,0]=aPrefix unless aString.begins_with?(aPrefix)
        aString
end
ensure_suffix(aValue=$/) click to toggle source
# File lib/buzztools/extend_string.rb, line 124
def ensure_suffix(aValue=$/)
        ensure_suffix!(aValue,self.dup)
end
ensure_suffix!(aSuffix=$/,aString=self) click to toggle source
# File lib/buzztools/extend_string.rb, line 119
def ensure_suffix!(aSuffix=$/,aString=self)
        aString.insert(-1,aSuffix) unless aString.ends_with?(aSuffix)
        aString
end
extract(aValue=$/) click to toggle source
# File lib/buzztools/extend_string.rb, line 51
def extract(aValue=$/)
        extract!(aValue,self.dup)
end
extract!(aValue=$/,aString=self) click to toggle source

Like bite, but returns the first match instead of the subject, and removes the match from the subject, modifying it

# File lib/buzztools/extend_string.rb, line 31
def extract!(aValue=$/,aString=self)
        if aValue.is_a? String
                if i = aString.index(aValue)
                        aString[i,aValue.length] = ''
                        return aValue
                else
                        return nil
                end
        elsif aValue.is_a? Regexp
                if md = aValue.match(aString)
                        aString[md.begin(0),md.end(0)-md.begin(0)] = ''
                        return md.to_s
                else
                        return nil
                end
        else
                return aString
        end
end
g?(*args) click to toggle source
# File lib/buzztools/extend_more.rb, line 7
def g?(*args)
        nil
end
has_tags?() click to toggle source
# File lib/buzztools/extend_string.rb, line 190
def has_tags?
        index(/<[a-zA-Z\-:0-9]+(\b|>)/) && (index('/>') || index('</'))               # contains an opening and closing tag
end
is_f?() click to toggle source
# File lib/buzztools/extend_string.rb, line 144
def is_f?
        self.to_float(false) and true
end
is_i?() click to toggle source
# File lib/buzztools/extend_string.rb, line 134
def is_i?
        self.to_integer(false) and true
end
iso8601ms() click to toggle source
# File lib/buzztools/extend_time.rb, line 120
def iso8601ms
        iso8601(3)
end
midnight()
Alias for: beginning_of_day
pad_left(value) click to toggle source
# File lib/buzztools/extend_string.rb, line 10
def pad_left(value)
        increase = value-self.length
        return self if increase==0
        if increase > 0
                return self + ' '*increase
        else
                return self[0,value]
        end
end
pad_right(value) click to toggle source
# File lib/buzztools/extend_string.rb, line 20
def pad_right(value)
        increase = value-self.length
        return self if increase==0
        if increase > 0
                return ' '*increase + self
        else
                return self[0,value]
        end
end
relative_url?() click to toggle source
# File lib/buzztools/extend_string.rb, line 198
def relative_url?
        !begins_with?('http') || !begins_with?('/')
end
scan_md(aPattern) click to toggle source

like scan but returns array of MatchData's. doesn't yet support blocks

# File lib/buzztools/extend_string.rb, line 150
def scan_md(aPattern)
        result = []
        self.scan(aPattern) {|s| result << $~ }
        result
end
seconds_since_midnight() click to toggle source
# File lib/buzztools/extend_time.rb, line 41
def seconds_since_midnight
        self.to_i - self.change(:hour => 0).to_i + (self.usec/1.0e+6)
end
snake_case() click to toggle source
# File lib/buzztools/extend_string.rb, line 194
def snake_case
        underscore.tr(' ','_')
end
split3(aPattern,aOccurence=0) { |*parts| ... } click to toggle source

given ('abcdefg','c.*?e') returns ['ab','cde','fg'] so you can manipulate the head, match and tail seperately, and potentially rejoin

# File lib/buzztools/extend_string.rb, line 211
def split3(aPattern,aOccurence=0)
        aString = self
        matches = aString.scan_md(aPattern)
        match = matches[aOccurence]
        parts = (match ? [match.pre_match,match.to_s,match.post_match] : [aString,nil,''])

        if !block_given?      # return head,match,tail
                parts
        else                                          # return string
                parts[1] = yield *parts if match
                parts.join
        end
end
time_numeric() click to toggle source
# File lib/buzztools/extend_time.rb, line 93
def time_numeric
        self.strftime('%H%M%S')
end
to_b(aDefault=false) click to toggle source
# File lib/buzztools/extend_bignum.rb, line 3
def to_b(aDefault=false)
        self==0 ? false : true
end
to_file(aFilename) click to toggle source
# File lib/buzztools/extend_string.rb, line 202
def to_file(aFilename)
        File.open(aFilename,'wb') {|file| file.write self }
end
to_float(aDefault=nil) click to toggle source
# File lib/buzztools/extend_string.rb, line 138
def to_float(aDefault=nil)
        t = self.strip
        return aDefault if !(t =~ /(\+|-)?([0-9]+\.?[0-9]*|\.[0-9]+)([eE](\+|-)?[0-9]+)?/)
        return t.to_f
end
to_integer(aDefault=nil) click to toggle source
# File lib/buzztools/extend_string.rb, line 128
def to_integer(aDefault=nil)
        t = self.strip
        return aDefault if t.empty? || !t.index(/^-{0,1}[0-9]+$/)
        return t.to_i
end
to_ms() click to toggle source
# File lib/buzztools/extend_bignum.rb, line 7
def to_ms # eg. for 1.minute.to_ms
        self*1000.0
end
to_nil() click to toggle source
# File lib/buzztools/to_nil.rb, line 2
def to_nil
        self.empty? ? nil : self
end
to_range(aMin,aMax=nil,aDefault=nil) click to toggle source
# File lib/buzztools/extend_fixnum.rb, line 7
def to_range(aMin,aMax=nil,aDefault=nil)
        (!aMin || (self >= aMin)) && (!aMax || (self <= aMax)) ? self : aDefault
end
to_sql_format() click to toggle source
# File lib/buzztools/extend_time.rb, line 101
def to_sql_format # was to_sql, but clashed with Rails 3
        self.strftime('%Y-%m-%d %H:%M:%S')
end
to_universal() click to toggle source
# File lib/buzztools/extend_time.rb, line 83
def to_universal
        self.strftime("%d %b %Y")
end
to_w3c() click to toggle source
# File lib/buzztools/extend_time.rb, line 105
def to_w3c
        utc.strftime("%Y-%m-%dT%H:%M:%S+00:00")
end
to_zone(aHours=nil) click to toggle source

This sets the zone without affecting the hour or day Useful for building a time object eg. New Year in Sydney : Time.new(2016,1,1).to_zone(10)

# File lib/buzztools/extend_time.rb, line 133
def to_zone(aHours=nil)
        aHours ||= utc_offset/3600.0
        self.in_time_zone(aHours)+self.utc_offset-aHours.to_i.hours
end
urlize(aSlashChar='+',aRemove=nil,aKeepExtensions=nil) click to toggle source
# File lib/buzztools/extend_string.rb, line 168
def urlize(aSlashChar='+',aRemove=nil,aKeepExtensions=nil)
        aKeepExtensions=URLIZE_EXTENSIONS if !aKeepExtensions
        aRemove=URLIZE_REMOVE if !aRemove
        return self if self.empty?
        result = self.downcase
        ext = nil
        if (aKeepExtensions!=:none) && last_dot = result.rindex('.')
                if (ext_len = result.length-last_dot-1) <= 4 # preserve extension without dot if <= 4 chars long
                        ext = result[last_dot+1..-1]
                        ext = nil unless aKeepExtensions==:all || (aKeepExtensions.is_a?(Array) && aKeepExtensions.include?(ext))
                        result = result[0,last_dot] if ext
                end
        end

        result = result.gsub(URLIZE_SEPARATORS,'-')
        result = result.gsub(aRemove,'').sub(/-+$/,'').sub(/^-+/,'')
        result.gsub!('/',aSlashChar) unless aSlashChar=='/'
        result.gsub!(/-{2,}/,'-')
        result += '.'+ext if ext
        result
end
zoneless() click to toggle source

“zoneless time” is a way of representing a time and date eg. 1am 1/1/1970 regardless of timezone. This is done by converting it to the same time and date, but with the utc flag set This means that Time.new(1970,1,1).zoneless.to_i will return the same value on any machine

# File lib/buzztools/extend_time.rb, line 127
def zoneless
        (self + self.utc_offset).utc
end