require 'json' class Array def to_flat_file_row options = { :delimeter => ',', :enclosed_by => '' } self.inject("") do |csv, item| csv << "#{options[:enclosed_by]}#{item}#{options[:enclosed_by]}#{options[:delimeter]}" end.chop end end class String def self.random_of_length length length.times.inject("") {|str| str << (rand(26) + 97).chr } end end class Integer def as_cost self / 100.0 end def in_hundredths self.to_f.in_hundredths end def to_currency self.to_f.to_currency end end class Float def as_cost self/100.0 end def in_hundredths return 0 if self == 0 val = "#{self/60.0}.#{((100.0*(self.modulo(60.0)))/60.0).to_s.rjust(2, '0')}" BigDecimal.new(val, 2).round(2).to_f end def to_currency int, frac = sprintf('%0.2f', self.round(2)).split('.') num = int.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, '\\1,') "$#{num}.#{frac}" end end class Range def split_by_step(step) current_min = min arr = [] while (current_min + step) <= max current_max = current_min + step arr << (current_min..current_max) current_min = (current_max + 1) end arr << (current_min..max) unless current_min > max arr end end class Hash XML_TYPE_NAMES = { "Symbol" => "symbol", "Fixnum" => "integer", "Bignum" => "integer", "BigDecimal" => "decimal", "Float" => "float", "TrueClass" => "boolean", "FalseClass" => "boolean", "Date" => "date", "DateTime" => "datetime", "Time" => "datetime", "ActiveSupport::TimeWithZone" => "datetime" } XML_FORMATTING = { "symbol" => Proc.new { |symbol| symbol.to_s }, "date" => Proc.new { |date| date.strftime('%d/%m/%Y') }, "datetime" => Proc.new { |time| time.xmlschema }, "yaml" => Proc.new { |yaml| yaml.to_yaml } } def limit_to_keys(limit_keys) dup.limit_to_keys!(limit_keys) end def limit_to_keys!(limit_keys) keys.each { |key| delete(key) unless limit_keys.include? key } self end def soft_delete(key) cloned_hash = deep_clone cloned_hash.delete(key) cloned_hash end def deep_clone Marshal::load(Marshal.dump(self)) end # Return a new hash with all keys converted to strings. def stringify_keys dup.stringify_keys! end # Destructively convert all keys to strings. def stringify_keys! keys.each do |key| self[key.to_s] = delete(key) end self end # Return a new hash with all keys converted to symbols, as long as # they respond to +to_sym+. def symbolize_keys dup.symbolize_keys! end # Destructively convert all keys to symbols, as long as they respond # to +to_sym+. def symbolize_keys! keys.each do |key| self[(key.to_sym rescue key) || key] = delete(key) end self end def diff(other) self.keys.inject({}) do |memo, key| unless self[key] == other[key] memo[key] = other[key] end memo end end def merge_add_values(other_hash) self.each do |k, v| self[k] += other_hash[k] if self[k] and other_hash[k] end self end end class Numeric def minutes self * 60 end alias :minute :minutes def hours self * 3600 end alias :hour :hours def days self * 24.hours end alias :day :days end