If you do printf debugging, this adds pretty colors and only shows for the user requesting the logging
# if you want to customize, redefine in initializers
# passenger does not define ENV['USER']
USER=ENV['HOME'].split('/').last

#usage:  my_log 'kbrock', 'UserController#logout', name
#only for me, will log 
def my_log(*args)
  who=args.shift #determine who wants to see this
  if who.nil? || who == USER
    theme=args.shift
    params = args.join ' ' || ''
    params += ' ' + yield if block_given?
    message="\e[1;34m#{theme}\e[0m #{params}"
    Rails.logger.debug(message)
    puts(message) unless Rails.env.test?
  end
end

If you do printf debugging, this adds pretty colors and only shows for the user requesting the logging

# if you want to customize, redefine in initializers
# passenger does not define ENV['USER']
USER=ENV['HOME'].split('/').last

#usage:  my_log 'kbrock', 'UserController#logout', name
#only for me, will log 
def my_log(*args)
  who=args.shift #determine who wants to see this
  if who.nil? || who == USER
    theme=args.shift
    params = args.join ' ' || ''
    params += ' ' + yield if block_given?
    message="\e[1;34m#{theme}\e[0m #{params}"
    Rails.logger.debug(message)
    puts(message) unless Rails.env.test?
  end
end
Private Browsing or cleared your cookies?

heh - go to flash player preferences to see the stuff that you missed.

Private Browsing or cleared your cookies?

heh - go to flash player preferences to see the stuff that you missed.

Tests rebuild database which takes a bit of time. I hacked Rakefile to not rebuild database every time.

Rake::Task['features'].clear_prerequisites   rescue nil # For some super weird reason this fails for some...
Rake::Task['default'].clear_prerequisites    rescue nil
Rake::Task['spec'].clear_prerequisites rescue nil

task :spec          => %w[db:abort_if_pending_migrations]
task :features      => %w[db:abort_if_pending_migrations]

desc "Run all tests and features"
task :default => %w(spec features)

Tests rebuild database which takes a bit of time. I hacked Rakefile to not rebuild database every time.


Rake::Task['features'].clear_prerequisites   rescue nil # For some super weird reason this fails for some...
Rake::Task['default'].clear_prerequisites    rescue nil
Rake::Task['spec'].clear_prerequisites rescue nil

task :spec          => %w[db:abort_if_pending_migrations]
task :features      => %w[db:abort_if_pending_migrations]

desc "Run all tests and features"
task :default => %w(spec features)
Rake task to generate model diagrams in a rails project

namespace :doc do
  desc "document db: (annotate, schema.rb, dot)"
  task :db=>%w(annotate_models db:schema:dump doc:dot)

  desc "Use railroad to generate graphviz dot files"
  task :dot do
    #tack on stuff at the top of the page
    FORMAT=%q{sed 's/graph\\[/  graph[page="8.5,11",\
            size="7.5,10",center=1];\
    node[shape=Mrecord,width="1.2",fillcolor="#cccccc",\
            style="filled", penwidth="2"]\
    edge [ minlen="1.2", penwidth="2"]\
    graph[/'}
  
    now=`rake db:version`.chomp.split(' ')[-1]
    models="doc/models#{now}.dot"
    #hide magic hides created_at, updated_at
   puts `railroad -liM --hide-magic|#{FORMAT}>#{models}`
  
    [models].each do |filename|
      filetype='pdf'
      outfile=filename.gsub('.dot',".#{filetype}")
      #create viewable file (graphviz must be installed)
      puts `dot -T#{filetype} #{filename} -o#{outfile}`

      #open the file using mac graphviz app
      puts `open #{filename} -a graphviz`
    end
  end
end

Rake task to generate model diagrams in a rails project


namespace :doc do
  desc "document db: (annotate, schema.rb, dot)"
  task :db=>%w(annotate_models db:schema:dump doc:dot)

  desc "Use railroad to generate graphviz dot files"
  task :dot do
    #tack on stuff at the top of the page
    FORMAT=%q{sed 's/graph\\[/  graph[page="8.5,11",\
            size="7.5,10",center=1];\
    node[shape=Mrecord,width="1.2",fillcolor="#cccccc",\
            style="filled", penwidth="2"]\
    edge [ minlen="1.2", penwidth="2"]\
    graph[/'}
  
    now=`rake db:version`.chomp.split(' ')[-1]
    models="doc/models#{now}.dot"
    #hide magic hides created_at, updated_at
   puts `railroad -liM --hide-magic|#{FORMAT}>#{models}`
  
    [models].each do |filename|
      filetype='pdf'
      outfile=filename.gsub('.dot',".#{filetype}")
      #create viewable file (graphviz must be installed)
      puts `dot -T#{filetype} #{filename} -o#{outfile}`

      #open the file using mac graphviz app
      puts `open #{filename} -a graphviz`
    end
  end
end
Easiest way I’ve fount to work with svn is to just use git as the client.
Most people explain how to converting svn to git. This lets me use git as a client for an svn server.
SVN_ROOT=ssh+svn://repo/opt/svn/repo/project1
git svn init -s $SVN_ROOT
git svn fetch
#git checkout -b svnrebase trunk
git rebase --onto trunk --root master
git svn dcommit

Easiest way I’ve fount to work with svn is to just use git as the client.

Most people explain how to converting svn to git. This lets me use git as a client for an svn server.

SVN_ROOT=ssh+svn://repo/opt/svn/repo/project1
git svn init -s $SVN_ROOT
git svn fetch
#git checkout -b svnrebase trunk
git rebase --onto trunk --root master
git svn dcommit

Collect for a hash

module Enumerable
  def hash_map
    hash = {}
    self.each {|o| hash.store(*yield(o))}
    hash
  end
end

my_hash = lines.hash_map {|l| l.split /:/}

Great suggestion on redit for creating a hash from other objects.

test helper

I added assert_empty to check that an array is empty.

But the line number from test helper.rb was the first line of the test helper, not the line in the test.

Instead, I wanted to see the actual failure as the first line. Welcome remove_me_from_trace(exception)

class Test::Unit::TestCase
  def assert_empty(*args)
    begin
      args.unshift []
      assert_equal *args
    rescue => e
      raise remove_me_from_trace(e)
    end
  end

  def remove_me_from_trace(e)
    x=e.backtrace.shift until (x =~ /test_helper.rb/ )
    e
  end
end

even better rake db:migrate

I normally don’t like hacking rails files directly, but this is the only way I could extend rake db:migrate to support a friendly VERSION.

railities/lib/tasks/database.rake on line 111.

  # was ENV["VERSION"] ? ENV["VERSION"].to_i : nil
  # looks up version based upon migration files
  def version_num
    version=ENV["VERSION"]
    if version.to_i==0 && version.present?
      matches=Dir["db/migrate/*#{ENV["VERSION"]}*"]
      if matches.length > 0
        #prune off directory name
        matches=matches.collect{|n| n.gsub(/^.*\//,'')}

        unless matches.length == 1
          raise "VERSION #{version} matches "+
            "#{matches.join(', ')}"
        end

        #prune off version num
        version=matches.first.gsub(/([^_]*)_.*$/) {$1}
        puts "VERSION=#{version}"
      end
    end
    version ? version.to_i : nil
  end

In 3 places (migrate, up, down), the version code is changed from

ENV["VERSION"] ? ENV["VERSION"].to_i : nil

to

version_num

Now rake db:migrate:down VERSION=create_photo works like a charm.

better rake db:migrate

I have been using a schell script so I don’t need to remember the long version number associated with ruby migrations.

#given a migration task, return the version
#e.g.: rake db:migrate:redo VERSION=$(mver create_photo)
function mver() {
  scr=${1:?Please specify migration action}
  ls db/migrate/*${scr}* | sed 's=^[^0-9]*\([0-9][^_]*\)_.*$=\1='
}
which will run migration 20100302214328_create_photos_and_folders.rb

Had an error about removing Object::ClassMethods.
I added the following to environment.rb to help me home in on the conflict.
RAILS_DEFAULT_LOGGER = Logger.new(STDOUT)
ActiveSupport::Dependencies::log_activity = true

Had an error about removing Object::ClassMethods.

I added the following to environment.rb to help me home in on the conflict.

RAILS_DEFAULT_LOGGER = Logger.new(STDOUT)
ActiveSupport::Dependencies::log_activity = true