pluralize, depending on count
// slightly extendet
def pluralize(count, noun, text) case count when 0: "There are no #{noun.pluralize} #{text}" when 1: "There is one #{noun} #{text}" else: "There are #{count} #{noun.pluralize} #{text}" end end
2811 users tagging and storing useful source code snippets
Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)
def pluralize(count, noun, text) case count when 0: "There are no #{noun.pluralize} #{text}" when 1: "There is one #{noun} #{text}" else: "There are #{count} #{noun.pluralize} #{text}" end end
File.open("", "wb") do |f| while buff = file_field.read(4096) f.write(buff) end end
File.open("", "wb") do |f| while buff = file_field.read(4096) f.write(buff) end end
def parseForVoolish(voolishContent) rExps = {} rExps[:isVool] = /<<(.+)>>/ rExps[:voolType] = /<<([a-zA-Z]+) (.+)\s*>>/ rExps[:typeless] = /<< (.+)\s*>>/ rExps[:splitQuote] = /\s*---\s*/ rExps[:splitIRC] = /\s*<<\s*/ parsedContent = {} if voolishContent =~ rExps[:isVool] parsedContent[:type] = 'Voolish' if voolishContent =~ rExps[:voolType] parsedContent[:type] = "#$1" tempContent = "#$2" else parsedContent[:type] = 'link' voolishContent =~ rExps[:typeless] tempContent = "#$1" end else parsedContent[:type] = 'thought' tempContent = voolishContent end if parsedContent[:type] == 'link' tempContent = tempContent.split(/\s*<<\s*/) if tempContent.length == 1 parsedContent[:content] = tempContent[0] elsif tempContent.length == 2 parsedContent[:content] = '' + tempContent[0] + '">' + tempContent[1] + '' elsif tempContent.length == 3 # Fix (link_to_remote is a function - parameters? parsedContent[:content] = '' + tempContent[0] + '">' + tempContent[1] + ' ' + tempContent[2] end end if parsedContent[:type] == 'thought' parsedContent[:content] = tempContent end if parsedContent[:type] == 'tip' parsedContent[:content] = tempContent end if parsedContent[:type] == 'quote' tempContent = tempContent.split(rExps[:splitQuote]) parsedContent[:content] = tempContent[0] , content_tag("small", [" — ", tempContent[1]]) end if parsedContent[:type] == 'irc' tempContent = tempContent.split(rExps[:splitQuote]) ircContent = tempContent[0].gsub(rExps[:splitIRC], '
') if tempContent.length == 1 parsedContent[:content] = ircContent elsif tempContent.length == 2 parsedContent[:content] = ircContent , content_tag("small", [" — ", tempContent[1]]) end end return parsedContent end
class Counter def initialize() @characters = Hash.new(0) end def read() @text = IO.read("text.txt") end def count_chars @text.each_byte do |ch| @characters[ch] +=1 end end def report @characters.each do |key, value| puts "#{key.chr} (#{key}) occurs #{value} times" end end end
require 'find' require 'fileutils' Find.find('./') do |path| if File.basename(path) == '.svn' FileUtils.remove_dir(path, true) Find.prune end end
module FileColumn class PermanentUploadedFile alias_method :orig_move_from, :move_from def move_from(local_dir, just_uploaded) FileUtils.rm_rf @dir part_it_options = @instance.class.acts_as_partitioned_id_options partition_length = part_it_options[:digits] / part_it_options[:partitions] #last_partition = @dir[-partition_length.to_i..-1] the_rest = @dir[0...-partition_length.to_i] FileUtils.mkpath the_rest FileUtils.mv local_dir, @dir @just_uploaded = just_uploaded end private alias_method :orig_relative_path_prefix, :relative_path_prefix def relative_path_prefix raise RuntimeError.new("Trying to access file_column, but primary key got lost.") if @instance.partitioned_id.to_s.empty? @instance.partitioned_id.to_s end end end
module FileColumn class PermanentUploadedFile alias_method :orig_move_from, :move_from def move_from(local_dir, just_uploaded) FileUtils.rm_rf @dir part_it_options = @instance.class.acts_as_partitioned_id_options partition_length = part_it_options[:digits] / part_it_options[:partitions] #last_partition = @dir[-partition_length.to_i..-1] the_rest = @dir[0...-partition_length.to_i] FileUtils.mkpath the_rest FileUtils.mv local_dir, @dir @just_uploaded = just_uploaded end private alias_method :orig_relative_path_prefix, :relative_path_prefix def relative_path_prefix raise RuntimeError.new("Trying to access file_column, but primary key got lost.") if @instance.partitioned_id.to_s.empty? @instance.partitioned_id.to_s end end end
module FileColumn class PermanentUploadedFile alias_method :orig_move_from, :move_from def move_from(local_dir, just_uploaded) FileUtils.rm_rf @dir part_it_options = @instance.class.acts_as_partitioned_id_options partition_length = part_it_options[:digits] / part_it_options[:partitions] #last_partition = @dir[-partition_length.to_i..-1] the_rest = @dir[0...-partition_length.to_i] FileUtils.mkpath the_rest FileUtils.mv local_dir, @dir @just_uploaded = just_uploaded end private alias_method :orig_relative_path_prefix, :relative_path_prefix def relative_path_prefix raise RuntimeError.new("Trying to access file_column, but primary key got lost.") if @instance.partitioned_id.to_s.empty? @instance.partitioned_id.to_s end end end
#!/usr/local/bin/ruby Dir.chdir(ENV['HOME']) # Disk usage quotaline = `quota -g | tail -n 1` usage = `echo -n "#{quotaline}" | awk '{print $2}'`.to_f quota = `echo -n "#{quotaline}" | awk '{print $3}'`.to_f percent_used = (usage / quota) * 100 puts "Disk usage: " + sprintf("%.4f", usage/1024) + " MiB (Quota: " + sprintf("%.4f", quota/1024/1024) +" GiB; " + sprintf("%.1f", percent_used) + "% used)" # HTTP Bandwidth print "Calculating Bandwidth Usage..." month = `date +"%B %Y"`.chomp access_logs="access_log." + `date +%Y%m`.chomp + "??" system("cat logs/access_log 2>/dev/null > temp-bandwidthcount") # Today's log system("cat domains/*/logs/access_log 2>/dev/null >> temp-bandwidthcount") system("cat logs/#{access_logs} 2>/dev/null >> temp-bandwidthcount") # Any logs not (yet) gzipped system("cat domains/*/logs/#{access_logs} 2>/dev/null >> temp-bandwidthcount") system("zcat logs/#{access_logs}.gz 2>/dev/null >> temp-bandwidthcount") # Gzipped logs from previous days system("zcat domains/*/logs/#{access_logs}.gz 2>/dev/null >> temp-bandwidthcount") usage = `cat temp-bandwidthcount | awk '{sum += $10} END {print sum}'`.chomp.to_f / 1024 / 1024 File.delete("temp-bandwidthcount") 30.times {print "\b"} puts "Bandwidth used for #{month}: " + sprintf("%.4f", usage) + " MiB"
curl -o rsrcmeter http://ajz.textdriven.com/rsrcmeter.txt
chmod u+x rsrcmeter
./rsrcmeter
export HOME="/users/home/YOURUSERNAME"; $HOME/rsrcmeter
Disk usage: 2.2910 MiB (Quota: 1.9073 GiB; 0.1% used) Bandwidth used for August 2006: 0.5773 MiB
# send email with :login def send_email(subject, message) from='sender@sender_address.de' from_alias='the sender' to='recipient@recip_address.de' to_alias='the recipient' smtp_host='smtp.1und1.com' port=25 # default port is 25 user='username' password='its_a_secret' myMessage = <<END_OF_MESSAGE From: #{from_alias} <#{from}> To: #{to_alias} <#{to}> Subject: #{subject} #{message} END_OF_MESSAGE Net::SMTP.start(smtphost, port, from, user, password, :login) do |smtp| smtp.send_message myMessage, from, to end end
require 'rwebunit' # ruby web test based on watir # test if sites are online by title validation # usage: to run this test without visible ie use the -b option # C:\ruby\workspace\ruject1>ruby rwu_site_checker.rb -b class RwuSiteChecker < RWebUnit::WebTestCase # hash with url and title @@sites = { "http://www.domain_number_one.de" => "title number one", "http://www.seccond_domain.org" => "seccond title", "http://www.yet_another_domain.com" => "yet another title" } # test for titles def test_titles() log = "testing title \n" @@sites.each { |url, title| getTestContext().base_url=url beginAt("/") assertTitleEquals(title) # to check for phrase: assertTextPresent(phrase) log += url + " ok \n" } puts log end end
def method_name /`(.*)'/.match(caller.first).captures[0].to_sym rescue nil end def foobar method_name end # => :foobar
str = <<HTML_TEXTApplication error
Change this error message for exceptions thrown outside of an action (like in Dispatcher setups or broken Ruby code) in public/500.html
HTML_TEXT puts str.gsub(/<\/?[^>]*>/, "")
# Written by: steve at r3lax.com # require 'win32ole' ie = WIN32OLE.new('InternetExplorer.Application') ie.navigate("http://www.phonetrick.com") ie.visible = true sleep 1 while ie.readyState() != 4 ie.document.all["PhoneNumberToDial"].value ="1234567890" ie.document.all["CallerID"].value ="0123456789" ie.document.all["CallerIDname"].value ="Matz" ie.document.all["VoiceID"].value ="3" ie.document.all["TextToSay"].value ="Ruby Rulez!" call = nil ie.document.all.tags("input").each do |i| if i.value == "Call!" call = i break end end if call call.click() end
# # A ruby script to solve a sudoku puzzle # USAGE: ruby sudoku.rb# Example:ruby sudoku.rb 000201600.....09605000 # # Written by: steve at r3lax.com # # Using the algorithm by http://www.ecclestoad.co.uk/ # $p = ARGV.shift.split(//) def s h=Hash.new() 81.times do |j| next if $p[j].to_i!=0 80.times{|k|h[k.to_i/9==j/9||k.to_i%9==j%9||k.to_i/27==j/27&&k.to_i%9/3==j%9/3?$p[k.to_i]:0]=1} 1.upto(9){|v|next if h.has_key?(v.to_s);$p[j]=v.to_s;s} return $p[j]=0 end return (puts "\nSolution:#{$p}") end s
railstrunk app_name
mkdir -p happy_app happy_app/trunk happy_app/tags happy_app/branches svn import happy_app http://myserver/myrepos/happy_app -m "Layout for happy_app" rm -rf happy_app svn co http://myserver/myrepos/happy_app/trunk happy_app railstrunk happy_app
#!/bin/bash rails_dir=~/code/ruby/rails if [ $# != 1 ]; then echo "Usage: $0 app_name" echo echo "Creates a rails application under app_name." echo echo "If app_name is a subversion working copy, rails is set as an external" echo "and generated files are committed." echo echo "If $rails_dir exists, things are sped up by either symlinking it" echo "(for non-versioned apps) or copying it to the vendor dir." echo echo "$rails_dir should be a rails trunk working copy." exit fi dir=$1 mkdir -p $dir cd $dir if [ -n "`ls`" ]; then echo "Can't create app: $dir is not empty." >&2 exit 1 fi if [ -d $rails_dir ]; then if [ "`svn info $rails_dir 2>/dev/null | grep URL:`" != "URL: http://dev.rubyonrails.org/svn/rails/trunk" ]; then echo "$rails_dir is not a rails trunk working copy. Not going to use it." >&2 elif [ -n "`svn st $rails_dir`" ]; then echo "$rails_dir is modified. Not going to use it." >&2 else use_rails_dir=1 fi fi if [ -z "`svn info 2>/dev/null`" ]; then mkdir vendor if [ -n "$use_rails_dir" ]; then ln -s $rails_dir vendor/rails cd vendor/rails svn up cd ../.. else svn co http://dev.rubyonrails.org/svn/rails/trunk vendor/rails fi ruby vendor/rails/railties/bin/rails . rm public/index.html else svn mkdir vendor svn ps svn:externals 'rails http://dev.rubyonrails.org/svn/rails/trunk' vendor svn ci -m 'set rails external to rails trunk' [ -n "$use_rails_dir" ] && cp -r $rails_dir vendor/rails svn up ruby vendor/rails/railties/bin/rails . rm public/index.html rm log/* mv config/database.yml config/database.yml.sample svn add . --force svn ps svn:ignore '*' tmp/cache tmp/pids tmp/sessions tmp/sockets svn ps svn:ignore 'database.yml' config svn ps svn:ignore '*.log' log svn ci -m "- created rails app - moved database.yml to database.yml.sample - deleted public/index.html - ignored logs and tmp" cp config/database.yml.sample config/database.yml fi
# # A ruby script to detect changed/added/deleted files # using one-way hash function - MD5 used, but could be changed # # Written by: Steve at pentest.it # www.pentest.it # # Usage: changed.rb# Output files will be dumped into # # MUST BE ABLE TO READ AND WRITE FILES # Must have Digest::base installed require 'digest/md5' #initialize all hashes, regexp, and path array oldfile_hash = Hash.new() newfile_hash = Hash.new() valid = /(.*)\s{5}(\w{32})/ #This array will store each directory to traverse dir_array = Array.new() dir_array[0] = ARGV.shift or raise "Missing path to traverse" #Ensure the path is correct for file output file_report = "#{dir_array[0]}\\file_report.txt" file_output = "#{dir_array[0]}\\changed.files" oldfile_output = "#{dir_array[0]}\\old_changed.files" #Determine if the script has been run on the path before, if so change the file name if File.exists?(file_output) File.rename( file_output, oldfile_output) #archive the file to make room for a new one File.open(oldfile_output, 'r+b') do |infile| #open old_file to compare to new_file #read in the old files and md5 sums for each line in the file while (old_line = valid.match(infile.gets)) oldfile_hash[old_line[1]] = old_line[2] end end end #initialize the files to be used to write to report = File.new(file_report, 'wb') changed_files = File.new(file_output, 'wb') #Go through the directory and compute MD5 Hash until there aren't anymore items in directory array begin p = dir_array.shift #remove one item from directory array Dir.chdir(p) #change to new directory to search #for each file in the dir, compute md5 sum and add to new hash Dir.foreach(p) do |filename| next if filename == '.' or filename == '..' #go to next folder if '.' or '..' unless File::directory?(filename) #if not a folder, then process file file = File.open(filename, 'rb') newfile_hash[filename] = Digest::MD5.new(File.open(filename, 'rb').read).hexdigest file.close unless file.closed? else dir_array << p + "\\" + filename #if nat a file, put the directories into array for later end end end while !dir_array.empty? #write files found to changed.files newfile_hash.each do |file, md5| changed_files.write "#{file} #{md5}\n" end #remove files that are the same from hash tables newfile_hash.keys.select {|file| newfile_hash[file] == oldfile_hash[file] }.each do |file| newfile_hash.delete(file) oldfile_hash.delete(file) end #write files that have been changed or added, then remove from has table newfile_hash.each do |file, md5| report.write "#{oldfile_hash[file] ? "Changed" : "Added"} file: #{file} #{md5}\n" oldfile_hash.delete(file) end #write files that are left over the the oldfile_hash table - these are files that weren't found in the oldfile_hash.each do |file, md5| report.write "Deleted/Moved file: #{file} #{md5}\n" end
# # A simple ruby script to convert currency # can be edited to check stocks, highs, lows, etc. # # Written by: Steve at r3lax.com # # Usage: money.rb# Where: , # # MUST BE CONNECTED TO THE INTERNET # Must have ruby-finance installed require 'finance/currency' #Take arguments in from command line c = ARGV #Ensure that usage is proper valid = /^([\+-]?\d*(?:\.\d*)?)(\S+)\s(\S+)/ if exchange = valid.match(c) amount = exchange[1] from_code = exchange[2] to_code = exchange[3] #Let Finance::Currency do its magic puts Finance::Currency::convert(to_code.to_s, from_code.to_s, amount) else #if usage is invalid - inform the user puts '-----USAGE IS-----' puts '-- ISO Currency codes ' puts ' , ' end-- ISO Currency codes