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

Tim Morgan http://timmorgan.org

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

Rails Array#add_condition Method

Lets you add a condition to a set of ActiveRecord conditions easily like this:

  conditions = ['active = ? and type = ?', true, 2]
  conditions.add_condition ['person_id = ?', 345]


class Array
  def add_condition(condition, conjunction='and')
    if condition.is_a? Array
      if self.empty?
        (self << condition).flatten!
      else
        self[0] += " #{conjunction} " + condition.shift
        (self << condition).flatten!
      end
    elsif condition.is_a? String
      self[0] += " #{conjunction} " + condition
    else
      raise "don't know how to handle this condition type"
    end
    self
  end
end

Dump a SQLite database

sqlite x.db .dump > output.sql

Find a table column on SQL Server

I often find myself looking for a specific database column that I have no idea where to find. Pouring over hundreds of tables is painful. One way to quickly narrow the search is to use this query...

SELECT name FROM sysobjects WHERE id IN ( SELECT id FROM syscolumns WHERE name = 'THE_COLUMN_NAME' )


...or, if you're unsure exactly what the column is named, but you suspect you know part of the name, then try...

SELECT name FROM sysobjects WHERE id IN ( SELECT id FROM syscolumns WHERE name like '%PART_OF_NAME%' )

Rails - Easily work with uppercase column names

I had to work with a legacy database with hundreds of tables with uppercase column names. Here is how I made my life a whole lot easier...

module ActiveRecord
  class MyCustomARClass < ActiveRecord::Base
  
    def self.reloadable?
      false
    end
    
    # all columns are uppercase
    set_primary_key 'ID'
    
    # convert to uppercase attribute if in existence
    # record.name => record.NAME
    # record.id => record.ID
    def method_missing(method_id, *args, &block)
      method_id = method_id.to_s.upcase if @attributes.include? method_id.to_s.upcase.gsub(/=/, '')
      super(method_id, *args, &block)
    end

    # strip leading and trailing spaces from attribute string values
    def read_attribute(attr_name)
      value = super(attr_name)
      value.is_a?(String) ? value.strip : value
    end

    class << self # Class methods
      
      private
        # allow for find_by and such to work with uppercase attributes
        # find_by_name => find_by_NAME
        # find_by_dob_and_height => find_by_DOB_and_HEIGHT
        def extract_attribute_names_from_match(match)
          match.captures.last.split('_and_').map { |name| name.upcase }
        end
    end
  end
end


This was defined in a plugin. Then, in each of my models I used the subclass instead of ActiveRecord::Base, like so...

class MyModel < ActiveRecord::MyCustomARClass
  # ...
end

Rails - Build Test Environment DB from Migrations

This custom rake task builds the test environment database from the migrations rather than the schema dump of the development database. This is especially handy if you have application data inserted via your migrations that you don't want to duplicate in fixtures.

You should be able to stick this in a file called "<whatever>.rake" and put it in your "tasks" directory.

To use as a plugin, create a directory in "vendor/plugins" and call it whatever you want. Inside, create a directory called "tasks". Place this code in a file there and call it whatever you want.

module Rake
  module TaskManager
    def redefine_task(task_class, args, &block)
      task_name, deps = resolve_args(args)
      task_name = task_class.scope_name(@scope, task_name)
      deps = [deps] unless deps.respond_to?(:to_ary)
      deps = deps.collect {|d| d.to_s }
      task = @tasks[task_name.to_s] = task_class.new(task_name, self)
      task.application = self
      task.add_comment(@last_comment)
      @last_comment = nil
      task.enhance(deps, &block)
      task
    end
  end
  class Task
    class << self
      def redefine_task(args, &block)
        Rake.application.redefine_task(self, args, &block)
      end
    end
  end
end

def redefine_task(args, &block)
  Rake::Task.redefine_task(args, &block)
end

namespace :db do
  namespace :test do

    desc 'Prepare the test database and migrate schema'
    redefine_task :prepare => :environment do
      Rake::Task['db:test:migrate_schema'].invoke
    end

    desc 'Use the migrations to create the test database'
    task :migrate_schema => 'db:test:purge' do
      ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
      ActiveRecord::Migrator.migrate("db/migrate/")
    end
  
  end
end
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS