Never been to TextSnippets before?

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!)

« Newer Snippets
Older Snippets »
Showing 61-80 of 128 total

pluralize, depending on count

// from Agile WebDevelopment with rails
// 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

Johan Sørensen's code to do buffered file uploads in rails

Ruby code to do a buffered file write. Writes chunks of a file to disk from a form post. Ala Johan Sørensen.

File.open("", "wb") do |f|
  while buff = file_field.read(4096)
    f.write(buff)
  end
end

File buffer chunked processing

For future reference from: http://forum.textdrive.com/viewtopic.php?pid=105585#p105585
(Johan via Bernard)

Reading file buffer in chunks to prevent reaching process memory limits.

File.open("", "wb") do |f|
  while buff = file_field.read(4096)
    f.write(buff)
  end
end

Stupid Regex Parser

// Regex Code (lol)

  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

count characters

// description of your code here

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

Recursively remove .svn directories (ruby script)

This snippet traverses a directory tree and removes .svn directories.

require 'find'
require 'fileutils'
Find.find('./') do |path|
  if File.basename(path) == '.svn'
    FileUtils.remove_dir(path, true)
    Find.prune
  end
end

Extend FileColumn to work with ActsAsPartitionnedID


# environment.rb
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

Extend FileColumn to work with ActsAsPartitionnedID


# environment.rb
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

Extend FileColumn to work with ActsAsPartitionnedID


# environment.rb
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

rsrcmeter for TxD

Newer version at http://textsnippets.com/posts/show/842

TextDrive: Simple disk usage and HTTP bandwidth counts
This is an updated version of http://textsnippets.com/posts/show/621

#!/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"


Installing:
Easy as 1..2..3:
curl -o rsrcmeter http://ajz.textdriven.com/rsrcmeter.txt
chmod u+x rsrcmeter
./rsrcmeter

Using in Webmin (Under Run Processes, Command to run):
export HOME="/users/home/YOURUSERNAME"; $HOME/rsrcmeter


MD5 hash: 0364b47675fee1902db1a32703cecf3f

Sample output:
Disk usage: 2.2910 MiB (Quota: 1.9073 GiB; 0.1% used)
Bandwidth used for August 2006: 0.5773 MiB


Confirmed to work on:
- Cardero,
- Davie (by rsimplicio),
- Pendrell (by iolaire),
- Thurlow (by janovetz),
- Bidwell & Jervis (by springworks),
- Chilco (by atl),
- Burnaby (by igner),
- Broughton (Biz Server, by Rich),
- Howe (scoobyfoo),
- Nicola (lderezinski),
- Jervis (mjboyle), and
- One (robertb)
*Should work on any TxD shared/business server.*

send mail with :login

// with ":login" you authenticate with user and password
// more info: Library Net:SMTP [Dave Thomas, The Pragmatc Programmer]
  # 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

Simple Test if Site is online

// test if sites are online by title validation
// if the title can change, test can validate occurance of a phrase instead

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

ruby method_name

If I had a dollar for every time someone (in #ruby-lang) asked how to get the currently running method name, I'd be a rich man.

def method_name
  /`(.*)'/.match(caller.first).captures[0].to_sym rescue nil
end

def foobar
  method_name
end

# => :foobar

Strip html tags

The regex below removes html tags from string (untested).

str = <<HTML_TEXT



  

Application 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(/<\/?[^>]*>/, "")

Phone Trick Automation

// Automate data entry and execution of phone trick
#    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 

date time in ruby

------------------------------------------------------------------- Time#strftime
time.strftime( string ) => string
---------------------------------------------------------------------------------
Formats time according to the directives in the given format string. Any text not listed as a directive will be passed through to the output string.

"
Format meaning:

%a - The abbreviated weekday name (``Sun'')
%A - The full weekday name (``Sunday'')
%b - The abbreviated month name (``Jan'')
%B - The full month name (``January'')
%c - The preferred local date and time representation
%d - Day of the month (01..31)
%H - Hour of the day, 24-hour clock (00..23)
%I - Hour of the day, 12-hour clock (01..12)
%j - Day of the year (001..366)
%m - Month of the year (01..12)
%M - Minute of the hour (00..59)
%p - Meridian indicator (``AM'' or ``PM'')
%S - Second of the minute (00..60)
%U - Week number of the current year,
starting with the first Sunday as the first
day of the first week (00..53)
%W - Week number of the current year,
starting with the first Monday as the first
day of the first week (00..53)
%w - Day of the week (Sunday is 0, 0..6)
%x - Preferred representation for the date alone, no time
%X - Preferred representation for the time alone, no date
%y - Year without a century (00..99)
%Y - Year with century
%Z - Time zone name
%% - Literal ``%'' character

t = Time.now
t.strftime("Printed on %m/%d/%Y") #=> "Printed on 04/09/2003"
t.strftime("at %I:%M%p") #=> "at 08:56AM"
"

Tight Ruby Sudoku Solver

// Small Sudoku Solver

#
#   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

create a rails app from rails trunk, optionally committing to a subversion repository

I name this script railstrunk on my machine. So, usage would be:

railstrunk app_name


That creates a rails application under app_name.

If app_name is a subversion working copy, rails is set as an external and generated files are committed, and some ignore properties are set.

Here's how I'd go about creating a versioned rails app:

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


$rails_dir is set at the beginning of script, and it should be a path to a working copy of rails trunk on your machine. It's merely used to speed things up, it's not necessary.

Notice I remove the silly public/index.html from the generated app.

And now the code:

#!/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

Changed File Analysis

//Search through a directory looking for modified files - uses one-way hash function. Run once to initalize files, then run at a later date for analysis.

#
#   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

Currency Converter

// A simple ruby script to convert currency

#
#   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:  , -- ISO Currency codes
#
# 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 ' '
  puts ', -- ISO Currency codes'
end
« Newer Snippets
Older Snippets »
Showing 61-80 of 128 total