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

sample

// description of your code here

// insert code here..

Cheat Gem for Ruby and Rails

Install and set up cheat for mac os x and TextMate
# install
sudo gem install cheat

# open TextMate
# open TextMate's bundle editor
# create a new command
# put the following code in the body
word=${TM_SELECTED_TEXT:-$TM_CURRENT_WORD}
echo "<html><head><title>Cheat Sheet for $word</title></head><body><pre>";
/usr/bin/cheat $word;
echo "</pre></body></html>";
# may have to edit path to where you intalled cheat, change /usr/bin/cheat to output of 'which cheat'
# change the output to Show as HTML
# click on activation and set it to a keyboard shortcut (such as ctrl-c)
# and your done when you want to see the cheat sheet for a selected item just highlight and ctrl-c

Mergesort

Mergesort implemented in Ruby. Because of it's performance not really suitable for productive use. (blog entry)

class Array
  def mergesort(&cmp)
    if cmp == nil
      cmp = lambda { |a, b| a <=> b }
    end
    if size <= 1
      self.dup
    else
       halves = split.map{ |half|
        half.mergesort(&cmp)
      }
      merge(*halves, &cmp)
    end
  end

 
  protected
  def split
    n = (length / 2).floor - 1
    [self[0..n], self[n+1..-1]]
  end

  def merge(first, second, &predicate)
    result = []
    until first.empty? || second.empty?
     if predicate.call(first.first, second.first) <= 0
        result << first.shift
      else
        result << second.shift
      end 
    end
    result.concat(first).concat(second)
  end
end

Stable Sort

Stable sort method for the Array class. Acts like the original sort method and accepts blocks in the same way. (blog entry)

class Array
  def stable_sort
    n = 0
    c = lambda { |x| n+= 1; [x, n]}
    if block_given?
      sort { |a, b|
        yield(c.call(a), c.call(b))        
      }
    else
      sort_by &c
    end
  end
end

Removes Markup From String

Removes any markup from string
@somevar = somestring.gsub(/<\/?[^>]*>/, "")

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!