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

Custom Validation in ActiveRecord

// allows adding errors in methods other than validate

  def other_errors=(err)
    write_attribute(:other_errors,Array.new) if !self.other_errors
    self.other_errors[self.other_errors.length] = err
  end
	
  def other_errors
    read_attribute(:other_errors)
  end

  def validate
    if self.other_errors
      self.other_errors.each {|x| errors.add_to_base(x)}
      return
    end
    return if !errors.empty?
  end

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

ActiveRecord attribute calls interception

I need to intercept attribute calls and add some additional info to them.

class ActiveRecord::Base
  def self.multilingual_field(fieldname)
    module_eval <<-end_eval
      def #{fieldname}
        send("#{fieldname}_\#{Locale.language.short_name}")
      end

      def #{fieldname}=(value)
        send("#{fieldname}_\#{Locale.language.short_name}=",value)
      end
    end_eval
  end
end

Default content-type in Rails

I always forget this.

class ApplicationController < ActionController::Base
  include AuthenticatedSystem
  
  before_filter :set_encoding
  
  private
    def set_encoding
      @headers["Content-type"] ||= "text/html; charset=utf8"
    end
end

Typo dispatch.fcgi

#!/usr/local/bin/ruby
#
# You may specify the path to the FastCGI crash log (a log of unhandled
# exceptions which forced the FastCGI instance to exit, great for debugging)
# and the number of requests to process before running garbage collection.
#
# By default, the FastCGI crash log is RAILS_ROOT/log/fastcgi.crash.log
# and the GC period is nil (turned off).  A reasonable number of requests
# could range from 10-100 depending on the memory footprint of your app.
#
# Example:
#   # Default log path, normal GC behavior.
#   RailsFCGIHandler.process!
#
#   # Default log path, 50 requests between GC.
#   RailsFCGIHandler.process! nil, 50
#
#   # Custom log path, normal GC behavior.
#   RailsFCGIHandler.process! '/var/log/myapp_fcgi_crash.log'
#
require File.dirname(__FILE__) + "/../config/environment"
require 'fcgi_handler'

RailsFCGIHandler.process!

link_to_remote not calling "complete"

<ul>
<% @items.each do |item| %>
<li>
<%= link_to_remote(item.name, 
{	
:url => { 
:controller => 'security', 
:action => 'add_security', 
:description => item.name, 
:symbol => item.symbol
},
:update 	=> {:success=>'indexFundList', :failure=>'notice'},
:position	=> :bottom,
:loading 	=> "loading()",
:complete 	=> "completeAddIndexFund(request)"
})		-%>
</li>
<% end %>
</ul>

Import of old Instiki data to a new Instiki instance

Trying to import data from Instiki.app 10.2 to Instiki 11.0 (alpha). The follow error is occurring.

 % ./instiki/script/import_storage -t instiki-old/2500 -i instiki-old/rb_src -d mysql -o instiki-data.sql
/users/home/quidire/web/public/instiki-old/rb_src/app/models/chunks/engines.rb:3:in `require': No such file to load -- redcloth (LoadError)
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/chunks/engines.rb:3
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/wiki_content.rb:2:in `require'
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/wiki_content.rb:2
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/revision.rb:2:in `require'
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/revision.rb:2
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/page.rb:3:in `require'
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/page.rb:3
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/web.rb:2:in `require'
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/web.rb:2
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/wiki_service.rb:7:in `require'
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/wiki_service.rb:7
        from ./instiki/script/import_storage:96:in `require'
        from ./instiki/script/import_storage:96

Select a State in Rails

<%= select(:shipaddress, :state, [ 	
	['Select a State', 'None'],
	['Alabama', 'AL'], 
	['Alaska', 'AK'],
	['Arizona', 'AZ'],
	['Arkansas', 'AR'], 
	['California', 'CA'], 
	['Colorado', 'CO'], 
	['Connecticut', 'CT'], 
	['Delaware', 'DE'], 
	['District Of Columbia', 'DC'], 
	['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']]) %>

start my lighttpd-based rails app

/usr/local/sbin/lighttpd -f /home/avshop/lighttpd/lighttpd.conf