PageRenderTime 39ms CodeModel.GetById 21ms app.highlight 15ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/wwmd/class_extensions/extensions_base.rb

http://github.com/miketracy/wwmd
Ruby | 252 lines | 187 code | 30 blank | 35 comment | 11 complexity | b276662cf31d9da7c852b0437c1cab0a MD5 | raw file
  1require 'htmlentities'
  2
  3=begin rdoc
  4let's re-open everything!
  5=end
  6
  7require 'uri'
  8
  9class Numeric
 10  # return binary representation of <tt>length</tt> size padded with \x00
 11  #  length:  length in bytes to return (padded with least signficant \x00
 12  #  reverse: reverse the byte order
 13  def to_bin (len,rev = false)
 14    str = ""
 15    bignum = self
 16    1.upto(len) do |i|
 17      str << (bignum & 0xFF).to_n8
 18      bignum = bignum >> 8  
 19    end
 20    return str.reverse if rev
 21    return str
 22  end
 23
 24  # integer to ip address
 25  def int_to_ip
 26    [24, 16, 8, 0].map { |b| (self >> b) & 255 }.join('.')
 27  end
 28
 29  # integer to mac address [uses ':' as delimiter]
 30  def int_to_mac
 31    [40,32,24,16,8,0].map { |b| ((self >> b) & 255).to_s(16).rjust(2,"0") }.join(":")
 32  end
 33end
 34
 35class String
 36
 37  def hexify
 38    self.unpack("H*").first.upcase
 39  end
 40
 41  def unhexify
 42    [self].pack("H*")
 43  end
 44  alias_method :dehexify,:unhexify
 45
 46  def strip_up
 47    self.gsub(/[^\x20-\x7e,\n]/,"").gsub(/^\n/,"")
 48  end
 49
 50  # ip address to int
 51  def ip_to_int
 52    self.split('.').inject(0) { |a,e| (a << 8) + e.to_i }
 53  end
 54
 55  # mac address to int [uses ':' as delimiter]
 56  def mac_to_int
 57    self.split(':').inject(0) { |a,e| (a << 8) + e.to_i(16) }
 58  end
 59
 60  # return true or false for <tt>string.match</tt>  
 61  def contains?(rexp)
 62    return !self.match(rexp).nil?
 63  end
 64
 65  # strip the string and return true if empty
 66  def empty?
 67    return self.strip == ''
 68  end
 69
 70  # return everything in the string (url) before the first get param
 71  ## "http://foo.bar.com/page.asp?somearg=foo&otherarg=bar".clip  
 72  ## => "http://foo.bar.com/page.asp"
 73  def clip(pref="?")
 74    if (v = self.index(pref))
 75      return self[0..(v-1)]
 76    end
 77    return self
 78  end
 79
 80  # return everything in the string (url) after the first get parameter
 81  # without the leading '?'
 82  #
 83  # pass true as the second param to also get back the ?
 84  ## "http://foo.bar.com/page.asp?somearg=foo&otherarg=bar".clop 
 85  ## => "somearg=foo&otherarg=bar"
 86  def clop(pref="?",preftoo=false)
 87    (preftoo == false) ? add = "" : add = pref
 88    if (v = self.index(pref))
 89      return add + self[(v+1)..-1]
 90    end
 91    return nil
 92  end
 93
 94  def clopp; self.clop("?",true); end #:nodoc:
 95
 96  def clopa
 97    return [self.clip,self.clop]
 98  end
 99
100  alias_method :clipa, :clopa
101
102  # File.dirname with a trailing slash
103  def dirname
104    return self if self.match(/\/$/)
105    File.dirname(self) + "/"
106  end
107
108  # File.basename
109  def basename(ext=nil)
110    if ext
111      File.basename(self,ext)
112    else
113      File.basename(self)
114    end
115  end
116
117  def extname
118    self.split('.').last
119  end
120
121  # write string to passed filename
122  # if filename is nil? will raise an error
123  def write(fname=nil)
124    raise "filename required" unless fname
125    File.write(fname,self)
126    self
127  end
128
129  # parse passed GET param string into a form and return the FormArray object
130  def to_form(action=nil)
131    if self.split("\n").size > 1
132      return self.to_form_from_show
133    end
134    ret = FormArray.new
135    self.split("&").each do |x|
136      y = x.split("=",2)
137      ret.add(y[0].to_s,y[1].to_s)
138#      ret[y[0].to_s] = y[1].to_s
139#      ret.extend!(y[0].to_s,y[1].to_s)
140    end
141    ret.action = action if action
142    return ret
143  end
144
145  def to_form_from_show
146    self.split("\n").map { |a|
147      key,val = a.split("=",2)
148      key = key.split(" ")[-1]
149      val = val.strip if val
150      ["#{key}=#{val}"]
151    }.join("&").to_form.squeeze_keys!
152  end
153
154  def mform
155    return self.gsub("\n","").to_form
156  end
157
158  def to_form_from_req
159#    self.split("\x0d\x0a\x0d\x0a")[1].to_form
160    self.split("\n\n")[1].to_form
161  end
162  alias_method :to_ffr, :to_form_from_req
163
164  # create filename from url changing "/" to "_"
165  def to_fn(ext=nil)
166    ret = self.clip.split("/")[3..-1].join("_")
167    ret += ".#{ext}" if not ext.nil?
168    return ret
169  end
170
171  # strip html tags from string
172  def strip_html
173    self.gsub(/<\/?[^>]*>/, "")
174  end
175
176  # range or int
177  def head(c=5)
178    if c.kind_of?(Range) then
179      range = c
180    else
181      range = (0..(c - 1))
182    end
183    self.split("\n")[range].join("\n")
184  end
185
186  # return a literal regexp object for this string
187  #
188  # escape regexp operators
189  def to_regexp
190    return Regexp.new(self.gsub(/([\[\]\{\}\(\)\*\$\?])/) { |x| '\\' + x })
191  end
192
193  # check if this string is a guid
194  def is_guid?
195    begin
196      Guid.from_s(self)
197    rescue => e
198      return false
199    end
200    return true
201  end
202
203  def md5
204    Digest::MD5.digest(self).hexify
205  end
206
207  def sha1
208    Digest::SHA1.digest(self).hexify
209  end
210
211  def sha256
212    Digest::SHA256.digest(self).hexify
213  end
214
215  def sha512
216    Digest::SHA512.digest(self).hexify
217  end
218
219  def pbcopy
220    IO.popen('pbcopy', 'r+') { |c| c.print self }
221  end
222end
223
224class Array
225  # grep each element of an array for the passed regular expression
226  # and return an Array of matches
227  # (only works one deep)
228  def each_grep(regex)
229    ret = []
230    self.each { |e| ret << e.grep(regex) }
231    return ret
232  end
233
234  # join the array with "\n" and write to a file
235  def to_file(filename)
236    File.write(filename,self.join("\n"))
237  end
238end
239
240class File
241  # write string to file
242  def self.write(filename,contents)
243    fout = File.open(filename,"w")
244    fout.print contents
245    fout.close
246  end
247end
248
249def pbpaste
250  %x[pbpaste]
251end
252