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-8 of 8 total  RSS 

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

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

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

Migrate rhtml views into erb views within subversion repository

From Brandon Keepers:

To migrate rhtml views into erb views within subversion repository:

Dir.glob('app/views/**/*.rhtml').each do |file|
  puts `svn mv #{file} #{file.gsub(/\.rhtml$/, '.erb')}`
end

Create classes at runtime

Dr Nic's Magic Models adds automatic ActiveRecord generation if you haven't defined a model, and for all ActiveRecords it can generate associations and validations on-the-fly based on the database schema (the table and column definitions).

It does this with some interesting Ruby meta-programming.

For example, if you want to create a new class at runtime, and assign it a superclass, try the following:

  def create_class(class_name, superclass, &block)
    klass = Class.new superclass, &block
    Object.const_set class_name, klass
  end


With this code, you can create a class as follows:

create_class('Person', ActiveRecord::Base) do
  set_table_name :people

  def fullname
    "#{firstname} #{lastname}" # assuming the people table has firstname,lastname columns
  end
end

« Newer Snippets
Older Snippets »
Showing 1-8 of 8 total  RSS