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

Strip html in ruby

def h(string)
  string.gsub(/<\/?[^>]*>/, "")
end

Passenger debugging

passenger-memory-stats
passenger-status


Put this in your conf file or in a virtual host. Helps with certain versions of rails and applications hanging.
RailsSpawnMethod conservative

iigydometyd3

zukgydometyd3 http://www.twine.com/user/lijupyceky96 Escort Bodykits [url=http://www.twine.com/user/rojahuluwo40] Escort Biloxi [/url] [url] http://www.twine.com/user/zefutahoxy85 [/url] [a] http://www.twine.com/user/qyqexevate58 [/a] zadgydometyd3

Log a backtrace in rails

If you're in a tough spot, debugging-wise, in your rails app, you can log your entire backtrace to see who called whom. Just put this snippet in the troublesome spot:

      begin
        raise "boom"
      rescue => detail
        RAILS_DEFAULT_LOGGER.info detail.backtrace.join("\n")
      end

Converting FileColumn store versions from old format to new format (/x) to (/0000/000x)

As of somewhen, the file_column rails plugin changed its storage layout and it doesn't seem to provide any way to migrate. Here's a simple snippet that'll do it.

Start an irb session in the directory where your file_column stores its files. By default that's RAILS_ROOT/public. In irb, run the following:

Dir['*/*/*'].grep(%r{[^/]+/[^/]+/\d+}).map { |s| [s.sub(/\d+$/, ''), $&.to_i] }\
  .map { |s, n| ["#{s}#{n}", (d = "#{s}%04d" % (n / 10000)), "#{d}/%04d" % (n % 10000)] }\
  .each { |f, d, t| `mkdir -p #{d} && mv #{f} #{t}` }


Or, as a migration

class UpgradeFileColumns < ActiveRecord::Migration
  def self.up
    # note I use a custom store path here
    Dir.chdir("#{RAILS_ROOT}/public/files")
    Dir['*/*/*'].grep(%r{[^/]+/[^/]+/\d+}).map { |s| [s.sub(/\d+$/, ''), $&.to_i] }\
      .map { |s, n| ["#{s}#{n}", (d = "#{s}%04d" % (n / 10000)), "#{d}/%04d" % (n % 10000)] }\
      .each { |f, d, t| `mkdir -p #{d} && mv #{f} #{t}` }
  end

  def self.down
  end
end


Convert all erb's to haml's in rails

for f in *.erb; do mv $f `basename $f .erb`.haml;done;

Ruby link_button_to

A helper for a link_button_to.

def link_button_to(name, options = {}, html_options = {})        
    url = url_for(options)          
    html_options["onclick"] = "javascript:document.location.href='#{url}'; return false;"
    html_options.merge!("type" => "button", "value" => name)        
    tag("input", html_options)    
end


Usage: <%= link_button_to "Edit", url_for(:action=>"edit"), :class=>"my_custom_class" -%>

Truncate text at a word boundry

// In application_helper
def snippet(text, wordcount, omission)
 text.split[0..(wordcount-1)].join(" ") + (text.split.size > wordcount ? " " + omission : "")
end


//Example usage in a view
<%= snippet(@post.body, 50, "#{link_to "Read more...", @post}") %>

ruby state options array


STATES = [
    [ "Alabama", "AL" ],
    [ "Alaska", "AK" ],
    [ "Arizona", "AZ" ],
    [ "Arkansas", "AR" ],
    [ "California", "CA" ],
    [ "Colorado", "CO" ],
    [ "Connecticut", "CT" ],
    [ "Delaware", "DE" ],
    [ "Florida", "FL" ],
    [ "Georgia", "GA" ],
    [ "Hawaii", "HI" ],
    [ "Idaho", "ID" ],
    [ "Illinois", "IL" ],
    [ "Indiana", "IN" ],
    [ "Iowa", "IA" ],
    [ "Kansas", "KS" ],
    [ "Kentucky", "KY" ],
    [ "Louisiana", "LA" ],
    [ "Maine", "ME" ],
    [ "Maryland", "MD" ],
    [ "Massachusetts", "MA" ],
    [ "Michigan", "MI" ],
    [ "Minnesota", "MN" ],
    [ "Mississippi", "MS" ],
    [ "Missouri", "MO" ],
    [ "Montana", "MT" ],
    [ "Nebraska", "NE" ],
    [ "Nevada", "NV" ],
    [ "New Hampshire", "NH" ],
    [ "New Jersey", "NJ" ],
    [ "New Mexico", "NM" ],
    [ "New York", "NY" ],
    [ "North Carolina", "NC" ],
    [ "North Dakota", "ND" ],
    [ "Ohio", "OH" ],
    [ "Oklahoma", "OK" ],
    [ "Oregon", "OR" ],
    [ "Pennsylvania", "PA" ],
    [ "Rhode Island", "RI" ],
    [ "South Carolina", "SC" ],
    [ "South Dakota", "SD" ],
    [ "Tennessee", "TN" ],
    [ "Texas", "TX" ],
    [ "Utah", "UT" ],
    [ "Vermont", "VT" ],
    [ "Virginia", "VA" ],
    [ "Washington", "WA" ],
    [ "West Virginia", "WV" ],
    [ "Wisconsin", "WI" ],
    [ "Wyoming", "WY" ]
  ]

<%= form.select :state, STATES, :include_blank => true %>

Friendlier Error Messages in Rails

// Just modify your error_messages_for in your views...

<%= error_messages_for :order, :header_message => "Please Try Again!", :message => "We had some problems saving your information:" %>