Never been to DZone Snippets 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

About this user

Dr Nic Williams http://drnicwilliams.com

« Newer Snippets
Older Snippets »
Showing 1-10 of 12 total  RSS 

Convert cp1252-> utf-8 character set (python and ruby)

Oooh, I hate character sets. Specifically that there are more than one of them. Here is a Ruby version of a Python script I found to convert cp1252 (aka windows-1252) into utf-8.

  def clean_up dirty_text
    newstr = ""
    dirty_text.length.times do |i|
      character = dirty_text[i]
      newstr += if character < 0x80
        character.chr
      elsif character < 0xC0
        "\xC2" + character.chr
      else
        "\xC3" + (character - 64).chr
      end
    end
    newstr
  end


The original Python script was (http://miscoranda.com/96):

#!/usr/bin/python
import sys
for c in sys.stdin.read(): 
   if ord(c) < 0x80: sys.stdout.write(c)
   elif ord(c) < 0xC0: sys.stdout.write('\xC2' + c)
   else: sys.stdout.write('\xC3' + chr(ord(c) - 64))

Array#pad!

My ri docco says there is an Array#pad! but runtime Ruby says there isn't. Bah. So I wrote one:

class Array
  def pad!(expected_length, pad_item = nil)
    while expected_length > length
      self << pad_item
    end
    self
  end
end

TextMate snippet for load_model methods in Rails controllers

With nested routes, I find I create a lot of controller methods like:

def load_user
  @user = User.find(params[:user_id]) if params[:user_id]


Here's a TextMate snippet, so you can just type: defmodel, TAB, user, TAB, and you're done.

Snippet:
def load_${1:model}
	@$1 = ${1/[[:alpha:]]+|(_)/(?1::\u$0)/g}.find(params[${2::$1_}id])${3: if params[:$1_id]}
end


Activation: defmodel
Scope: source.ruby.rails

I have this in the Ruby on Rails bundle, but you can put it anywhere. Its the scope that is important.

Upgrade rubygems and/or specific gems themselves via capistrano

When a latest RubyGems is released (e.g. 0.9.5 recently) or Rails (e.g. 2.0.2) you might want to push those upgrades to all your production machines.

Add these two tasks to your deploy.rb capistrano file (add namespaces for cap2.0 if you like)

  desc "Updates RubyGems version"
  task :gem_update_system do
    sudo "gem update --system"
  end

    
  desc "Install a RubyGem from remote source"
  task :gem_install do
    puts "USAGE: GEM=gemname cap gems_install" and next unless ENV['GEM']
    sudo "gem install #{ENV['GEM']} --no-ri --no-rdoc"
  end


To upgrade rubygems and rails, for example:

cap gem_update_system
GEM=rails cap gem_install

Checkout a Git clone of an SVN repository in parent folder

Here is a quick executable cmd that you run inside a folder checked out with Subversion. It will clone the repository using Git into the parent folder as &lt;projname&gt;.git

Stick this code into ~/bin/gitify and add ~/bin to your path:

#!/usr/bin/env ruby -wKU

# get svn info location
svnurl = `svn info | grep "^URL:"`.gsub('URL: ','').chomp

# project = basename
project = File.basename(Dir.pwd)

puts cmd = "git-svn clone #{svnurl} ../#{project}.git"

`#{cmd}`

Auto-populate socket value in rails database.yml using TextMate snippet


When using mysql for rails apps, you may need a
socket:
value. I can never remember mine. So I added a TextMate snippet to find it. (read below for non-TextMate)

Snippet text:

socket: `mysql_config --socket`


Activation:
socket:


Scope selector:
source.yaml - string


<h3>Usage:</h2>

In your database.yml, go to the line
socket: 
, delete any blank spaces til the cursor is at the colon, then press TAB and wait. The line will be updated with the socket location.


<h3>Non-TextMate</h3>

If you don't have textmate, you can get your socket location using:

mysql_config --socket


And paste the result into your database.yml

Dump postgres production data into development database

When bug requests come in, its great to grab a copy of the current production (or system test env) data and sync it into your development database.

Here's a capistrano recipe for postgresql:

desc "Dumps target database into development db"
task :sync_db do
  env   = ENV['RAILS_ENV'] || ENV['DB'] || 'production'
  file  = "#{application}.sql.bz2"
  remote_file = "#{shared}/log/#{file}"
  run "pg_dump --clean --no-owner --no-privileges -U#{db_user} -h#{db_host} #{db_name}_#{env} | bzip2 > #{file}" do |ch, stream, out|
    ch.send_data "#{db_password}\n" if out =~ /^Password:/
    puts out
  end
  puts rsync = "rsync #{user}@#{domain}:#{file} tmp"
  `#{rsync}`
  puts depackage = "bzcat tmp/#{file} | psql #{local_db_dev}"
  `#{depackage}`
end

Reset user password based on another users

When you first create an app you might not have time *cough* to add special user password reset features. Especially if you don't have many users.

Here's a quick script to set the password of a user to another user (say a manually created user 'tester' with a known password).

namespace :user do
  desc 'Reset user (USER=username) password to that of username "tester" (or FROM=username env)'
  task :reset => :environment do
    reset_username = ENV['USER']
    unless ENV['USER']
      puts 'Require "USER=username" for user to be reset'
      next
    end
    reset_user     = User.find_by_username reset_username
    unless reset_user
      puts "Cannot find user: #{reset_username}"
      next
    end
    from_username  = ENV['FROM'] || 'tester'
    from_user      = User.find_by_username from_username
    unless from_user
      puts "Cannot find user: #{from_username}"
      next
    end
    
    reset_user.crypted_password = from_user.crypted_password
    reset_user.salt             = from_user.salt
    reset_user  .save
    puts 'User password reset'
  end
end

Turn numbers into strings with thousands' separators

Turn numbers into strings with thousands' separators (from zenspider)

class Numeric
  def commify(dec='.', sep=',')
    num = to_s.sub(/\./, dec)
    dec = Regexp.escape dec
    num.reverse.gsub(/(\d\d\d)(?=\d)(?!\d*#{dec})/, "\\1#{sep}").reverse
  end
end


So, you get:

1233232423424.23423.commify # => "1,233,232,423,424.23"

Capistrano logs

To get the last n lines from a remote log file, use this task

Usage: cap log [-s lines=100] [-s rails_env=production]
So, "cap log" returns 100 lines from production.

desc "Returns last lines of log file. Usage: cap log [-s lines=100] [-s rails_env=production]"
task :log do
  lines     = configuration.variables[:lines] || 100
  rails_env = configuration.variables[:rails_env] || 'production'
  run "tail -n #{lines} #{app_dir}/log/#{rails_env}.log" do |ch, stream, out|
    puts out
  end
end

« Newer Snippets
Older Snippets »
Showing 1-10 of 12 total  RSS