Never been to CodeSnippets 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!)

Mongrel cluster starting after restart on Ubuntu GG

sudo mkdir /etc/mongrel_cluster
sudo ln -s /mnt/app/ticketsolve/shared/config/mongrel_cluster_new_production.yml /etc/mongrel_cluster/mongrel_cluster_new_production.yml
sudo cp /usr/bin/mongrel_cluster_ctl /etc/init.d/
sudo chmod +x /etc/init.d/mongrel_cluster_ctl
cd /etc/init.d/
sudo /usr/sbin/update-rc.d -f mongrel_cluster_ctl defaults

rmagick test

// Check if rmagick is installed properly by running gem list. Now we are going to test if rmagick works properly. Create a file called test_rmagick.rb, and copy and paste the code below.

#!/usr/bin/env ruby -wKU

# Test if rmagick is working properly or not.
# When run, this file creates a image file 'path.gif' in the same directory.

# the sample code is from http://rmagick.rubyforge.org/portfolio3.html

require 'rubygems'
require 'rmagick' # Don't use a capital 'R'.

canvas = Magick::Image.new(240, 300,
              Magick::HatchFill.new('white','lightcyan2'))
gc = Magick::Draw.new

gc.fill('red')
gc.stroke('blue')
gc.stroke_width(2)
gc.path('M120,150 h-75 a75,75 0 1, 0 75,-75 z')
gc.fill('yellow')
gc.path('M108.5,138.5 v-75 a75,75 0 0,0 -75,75 z')
gc.draw(canvas)

canvas.write('path.gif')

Lispify Ruby

// description of your code here

   require 'rubygems'  
   require 'parse_tree'  
   require 'ruby2ruby'  
     
   Sexp.class_eval do  
     def unbox  
       if length == 1  
         self.first  
       else  
         self  
       end  
     end  
   end  
     
   class Lispify < SexpProcessor  
     def initialize  
       super  
       self.auto_shift_type = true  
       self.require_empty   = false  
     end  
     
     def process_vcall(expr)  
       s(expr.first)  
     end  
     
     def process_call(expr)  
       expr = Sexp.from_array(expr)  
     
       first  = process(expr[0]).unbox  
       second = process(expr[2]).unbox  
     
       s(expr[1], first, second)  
     end  
     
     def process_array(expr)  
       process(expr.first)  
     end  
   end  


Which results in:


>> Lispify.new.process(ParseTree.translate(%q{ x + x * x - x }))
=> s(:-, s(:+, :x, s(:*, :x, :x)), :x)

Rails CSV Export



# require 'rubygems' if using this outside of Rails
require 'fastercsv'

def dump_csv
  @users = User.find(:all, :order => "lastname ASC")
  @outfile = "members_" + Time.now.strftime("%m-%d-%Y") + ".csv"
  
  csv_data = FasterCSV.generate do |csv|
    csv << [
    "Last Name",
    "First Name",
    "Username",
    "Email",
    "Company",
    "Phone",
    "Fax",
    "Address",
    "City",
    "State",
    "Zip Code"
    ]
    @users.each do |user|
      csv << [
      user.lastname,
      user.firstname,
      user.username,
      user.email,
      user.company,
      user.phone,
      user.fax,
      user.address + " " + user.cb_addresstwo,
      user.city,
      user.state,
      user.zip
      ]
    end
  end

  send_data csv_data,
    :type => 'text/csv; charset=iso-8859-1; header=present',
    :disposition => "attachment; filename=#{@outfile}"

  flash[:notice] = "Export complete!"
end

ActiveRecord reconnect to database

// my Merb consoles drop the db connection after the mysql timeout; I'd rather not reload the whole environment

ActiveRecord::Base.connection.reconnect!

battstatt.rb, an OS X Leopard battery stats grabber

A little ruby script to output stats on your OSX laptop. Works on Leopard, not sure about others.

#!/usr/bin/env ruby -wKU
res = Array.new
res = %x(/usr/sbin/ioreg -p IODeviceTree -n "battery" -w 0).grep(/Battery/)[0].match(/\{(.*)\}/)[1].split(',')
stats = Hash.new

res.each do |d| 
  key, val = d.split("=")
  key.downcase!.delete!(" ")
  if key =~ /\"(.*)\"/
    key = $1
  end
  stats[:"#{key}"] = val
end

puts
puts "-------------------------------"
puts "         Battery Stats"
puts "-------------------------------"
puts
stats.each { |k, v| puts "#{k} => #{v}" }
percentOfOriginal = (stats[:capacity].to_f / stats[:absolutemaxcapacity].to_f) * 100
puts "Battery capacity is currently #{sprintf("%.2f", percentOfOriginal)}% of original."

Install postgres gem on Mac OS X 10.5 (Leopard)

When upgrading or installing recent versions of the postgres ruby gem on Leopard the following error appears

	===========   WARNING   ===========

		You are building this extension on OS X without setting the
		ARCHFLAGS environment variable, and PostgreSQL does not appear
		to have been built as a universal binary. If you are seeing this
		message, that means that the build will probably fail.

		Try setting the environment variable ARCHFLAGS
		to '-arch i386' before building.

		For example:
		(in bash) $ export ARCHFLAGS='-arch i386'
		(in tcsh) $ setenv ARCHFLAGS '-arch i386'

		Then try building again.

		===================================


The trick is to set the ARCHFLAGS variable inside the sudo command using env.

sudo env ARCHFLAGS="-arch i386" gem install postgres

Suppress Warnings in Ruby

#!/usr/bin/env ruby

# Kernel#with_warnings_suppressed - Supresses warnings in a given block.
# Require this file to use it or run it directly to perform a self-test.
#
# Note: The test probably won't work on Windows (haven't tried it, but
#       IO.popen likely uses fork)
# 
# Author:: Rob Pitt
# Copyright:: Copyright (c) 2008 Rob Pitt
# License:: Free to use and modify so long as credit to previous author(s) is left in place.
#

module Kernel
  # Suppresses warnings within a given block.
  def with_warnings_suppressed
    saved_verbosity = $-v
    $-v = nil
    yield
  ensure
    $-v = saved_verbosity
  end
end

#--
# Kernel#with_warnings_suppressed self-test.
if $0 == __FILE__
  # Go here for reference on rspec: http://rspec.info/examples.html
  require 'rubygems'
  require 'spec'
  
  def warning_generator
    IO.popen( '-' ) do |io|
      if io # parent          
        return io.read
      else #child
        $stderr.reopen( $stdout )
        Object.const_set( 'MONKEY', 1 )
        Object.const_set( 'MONKEY', 2 )
      end
    end
  end
  
  describe Kernel do

    it "should supress warnings" do
      with_warnings_suppressed do 
        warning_generator
      end.should == ""
    end
    
    it "should restore the previous verbosity state when it's finished" do
      with_warnings_suppressed do 
        warning_generator
      end.should == ""
      warning_generator.should match( /warning: already initialized constant MONKEY/ )
    end
    
  end
    
end
#++

Add missing empty directories in .svn

Fix errors like
svn: Your .svn/text-base directory may be missing or corrupt; run 'svn cleanup' and try again
svn: Can't open file 'blabla/.svn/text-base/entries': No such file or directory

require 'pathname'

def recurse(dir)
  for child in dir.children
    next unless child.directory?              # ignore files
    next if child.basename.to_s == '.svn'     # ignore .svn directory
    next unless (child + '.svn').exist?       # ignore unadded directories
    text_base_dir = child + '.svn/text-base'  # path to text-base dir
    next if text_base_dir.exist?              # ignore existing text-base dirs
    text_base_dir.mkdir
    puts text_base_dir
    recurse child
  end
end

recurse Pathname.new('.')

lazy initialized boolean ruby 1.8.6

// lazily initialize a boolean accessor (requires ruby > 1.8.6)

  def attr?
    @attr = true unless instance_variable_defined? :@attr
    @attr
  end