Skip to content

Instantly share code, notes, and snippets.

@dreftymac
Last active December 20, 2015 02:49
Show Gist options
  • Save dreftymac/6059176 to your computer and use it in GitHub Desktop.
Save dreftymac/6059176 to your computer and use it in GitHub Desktop.
Ruby string expando methods
## main:
## - date: created="Monday, September 10, 2012, 11:13:12 AM"
## last: lastmod="Mon Jun 23 14:20:15 2014"
## desc: |
## Ruby String Addon methods
##
## seealso:
## href="./DreftymacAddonStringTest.rb"
## tymacid://tryruby.myruby.dreftymac.DreftymacAddonString.rb
## https://gist.github.com/dreftymac/6059176
### ------------------------------------------------------------------------
##{
module DreftymacAddonString
### ------------------------------------------------------------------------
module Base
##{
# remove leading indentation from string
def sgdedent()
indent = self.
split(/[\x0a\x0d]/).
select{ |line| line[/[^\s]+/] }.
map{ |line|(vxx=line[/^([\s]+)/].to_s.length;vxx==0;)? nil:vxx; }.
compact.
min
self.
gsub(/^#{' '*indent.to_i}/, '').
ljust(0).
to_s
end
##}
##{
## wrap balanced chars around a string
def sghug(str_hug='"')
ahug = [];
ahug = nil ||
["[ ]".split()].select{|vy|vy.any?{|vx|vx==(str_hug)}}[0]||
["{ }".split()].select{|vy|vy.any?{|vx|vx==(str_hug)}}[0]||
["< >".split()].select{|vy|vy.any?{|vx|vx==(str_hug)}}[0]||
["( )".split()].select{|vy|vy.any?{|vx|vx==(str_hug)}}[0]||
["<% %>".split()].select{|vy|vy.any?{|vx|vx==(str_hug)}}[0]||
["[% %]".split()].select{|vy|vy.any?{|vx|vx==(str_hug)}}[0]||
["/* */".split()].select{|vy|vy.any?{|vx|vx==(str_hug)}}[0]||
["<!-- -->".split()].select{|vy|vy.any?{|vx|vx==(str_hug)}}[0]||
["<!--- --->".split()].select{|vy|vy.any?{|vx|vx==(str_hug)}}[0]||
[str_hug]*2
;
ahug[0] + self.to_s + ahug[1];
end
##}
##{
## indent each line in a string with leading chars. prefix can be specified using integer or string
def sgindent(vraw=2)
if(vraw.class == Fixnum)
vraw = " " * vraw;
end
self.to_s.gsub(/^/,vraw);
end
##}
##{
## newline prefix beginning of string
def sgnp
("\n") + self.to_s
end
##}
##{
## newline at end of string
def sgnn
self.to_s + ("\n")
end
##}
##{
## convert fwd slash to backslash
def sgslashback
self.to_s.split(/\x2f/).join("\x5c")
end
alias :sgslashbak :sgslashback;
alias :sgbslash :sgslashback;
##}
##{
## convert backslash to fwd slash
def sgslashforward
self.to_s.split(/\x5c/).join("\x2f")
end
alias :sgslashfwd :sgslashforward;
alias :sgfslash :sgslashforward;
##}
##{
# slug-reformat string http://stackoverflow.com/questions/427102
def sgslug(sformat)
self.to_s.split(/[\W]+/).join('').downcase
end
##}
##{
# sprintf syntactic sugar
def sgspr(sformat)
sprintf(sformat, self.to_s())
end
##}
end
##
### ------------------------------------------------------------------------
module DSVString
##{
# add first-row-fieldnames to a dsv string
# Params:
# - delim: the dsv delimiter
# - fieldnames: array of fieldnames
def dsv_first_row_fieldnames(options = {})
options = {'delim' => ";;", 'fieldnames' => []}.merge(options)
options['fieldnames'].
join(options['delim']).
#concat("\n").
concat(self.to_s). ## self.to_s is a dsv string
to_s
end
##}
### <reg-fdef ddef="dsvload ;; parse dsv simpletable string and return an aoh">
##{
# load a dsv string into a native ruby data structure
# Params:
# - delim: dsv delimiter
# - has_names: true if first row has fieldnames
def dsvload(options = {})
## init
options = {
'delim' => ";;", ## string delimiter
'has_names'=> true, ## true if first row contains fieldnames
}.merge(options)
sraw = self.to_s.strip()
aout = []
sdelim = Regexp::quote( options["delim"] )
anames = %w[];
alines = [];
alines = sraw.split(/[\x0a\x0d]/).select{|vxx|vxx.strip()!=''};
bnames = options["has_names"]
##
if(! bnames) then
(0 .. alines[0].split(/\s*#{sdelim}\s*/).length()-1).
each{|vxx|anames<<"fld"+vxx.to_s()};
else
anames = alines.shift().split(/\s*#{sdelim}\s*/).map{|vxx|vxx.strip()};
end
##
alines.each{ |vxx|
vxx = vxx.split(/\s*#{sdelim}\s*/);
vals = vxx.map{|vyy| vyy.strip()};
rec = Hash[*anames.zip(vals).flatten];
aout << (rec)
}
return aout;
end
alias :dsv_load :dsvload;
##}
##{
# align delimiters in a dsv string
# Params:
# - delim: the dsv delimiter
# - padding: specify padding for columns
def dsvpretty(options = {})
options = {'delim' => ";;", 'padding' => ""}.merge(options)
string = self.to_s
rows = string.strip.split(/\n/).map{ |line| line.strip.split(options['delim']) }
columns_max_width = rows.map { |row| row.map(&:size) }.transpose.map(&:max)
columns_separator = options['padding'] + options['delim'] + options['padding']
rows.map do |row|
row.zip(columns_max_width).map do |cell, column_max_width|
cell.ljust(column_max_width)
end.join(columns_separator)
end.join("\n")
end
alias :dsv_pretty :dsvpretty
##}
end
##
### ------------------------------------------------------------------------
module FileIO
def sgfromfile(spath)
oFile = File.new(spath, "r");
alines = oFile.readlines().join();
oFile.close();
alines;
end
##
def sgtofile(spath,smode='w+')
sout = self.to_s;
otest = File.new(spath,smode);
otest.print(sout);
otest.close();
return spath
end
##
##{
def sgtofilebom(spath)
sout = "\uFEFF".to_s + self.to_s
sout.sgtofile(spath)
end
##}
end
##
end
##}
##{
class String
include DreftymacAddonString::Base
include DreftymacAddonString::FileIO
include DreftymacAddonString::DSVString
end
##}
##{
module Enumerable
##{
def dsvdump(delim=';;',mykeys=self[0].keys )
vout = ''
vout += mykeys.join(delim)
vout += "\n"
self.to_a.each { |row|
aout = []
mykeys.each{|skey|
aout << row[skey]
}
vout += aout.join(delim);
vout += "\n"
}
return vout
end
alias :dsv_dump :dsvdump
##}
end
##}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment