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

Using POP3 to Retrieve Email for Rails App

Put this in a file called "inbox" in the scripts/ directory of your Rails app. change the host, username, and password to match.

Set up a cron job to run this script every so often (frequency depends on your needs).

   1  
   2  #!/usr/bin/env ruby
   3  
   4  require 'net/pop'
   5  require File.dirname(__FILE__) + '/../config/environment'
   6  
   7  logger = RAILS_DEFAULT_LOGGER
   8  
   9  logger.info "Running Mail Importer..." 
  10  Net::POP3.start("localhost", nil, "username", "password") do |pop|
  11    if pop.mails.empty?
  12      logger.info "NO MAIL" 
  13    else
  14      pop.mails.each do |email|
  15        begin
  16          logger.info "receiving mail..." 
  17          Notifier.receive(email.pop)
  18          email.delete
  19        rescue Exception => e
  20          logger.error "Error receiving email at " + Time.now.to_s + "::: " + e.message
  21        end
  22      end
  23    end
  24  end
  25  logger.info "Finished Mail Importer." 
  26  

image_tag with popup for alt attribute

Firefox doesn't display a popup for the alt attribute for images. While this is according to spec, it's slightly annoying to put the same text in both the alt and the title. Put the following in your ApplicationHelper to copy the alt to the title for every image. Please don't tell me how wrong this is. I don't care.

   1  
   2  module ApplicationHelper
   3    def image_tag(location, options)
   4      options[:title] ||= options[:alt]
   5      super(location, options)
   6    end
   7  end

Fix for ActiveRecord SQL Server adapter dates

The SQL Server adapter for ActiveRecord uses Time objects to cast dates from the db. This fails for dates before 1970, thus some birthdates come back as nil. This is some kludge to use a DateTime in that case so we still get the value.

A better approach may be to convert this code to use DateTime objects exclusively, but I'm not sure of the speed implications of doing so. The code below first tries to cast the value to a Time object; if that fails, it tries a DateTime object; if that fails, it returns nil.

Stick this in a plugin to use with Rails.

   1  
   2  module ActiveRecord
   3    module ConnectionAdapters
   4      class ColumnWithIdentity
   5        def cast_to_time(value)
   6          return value if value.is_a?(Time) or value.is_a?(DateTime)
   7          time_array = ParseDate.parsedate(value)
   8          time_array[0] ||= 2000
   9          time_array[1] ||= 1
  10          time_array[2] ||= 1
  11          Time.send(Base.default_timezone, *time_array) rescue DateTime.new(*time_array[0..5]) rescue nil
  12        end
  13        def cast_to_datetime(value)
  14          if value.is_a?(Time) or value.is_a?(DateTime)
  15            if value.year != 0 and value.month != 0 and value.day != 0
  16              return value
  17            else
  18              return Time.mktime(2000, 1, 1, value.hour, value.min, value.sec) rescue nil
  19            end
  20          end
  21          return cast_to_time(value) if value.is_a?(Date) or value.is_a?(String) rescue nil
  22          value
  23        end
  24      end
  25    end
  26  end

Force output to download as a file in Rails

   1  
   2  response.headers['Content-Type'] = 'text/csv' # I've also seen this for CSV files: 'text/csv; charset=iso-8859-1; header=present'
   3  response.headers['Content-Disposition'] = 'attachment; filename=thefile.csv'

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...

   1  
   2  module ActiveRecord
   3    class MyCustomARClass < ActiveRecord::Base
   4    
   5      def self.reloadable?
   6        false
   7      end
   8      
   9      # all columns are uppercase
  10      set_primary_key 'ID'
  11      
  12      # convert to uppercase attribute if in existence
  13      # record.name => record.NAME
  14      # record.id => record.ID
  15      def method_missing(method_id, *args, &block)
  16        method_id = method_id.to_s.upcase if @attributes.include? method_id.to_s.upcase.gsub(/=/, '')
  17        super(method_id, *args, &block)
  18      end
  19  
  20      # strip leading and trailing spaces from attribute string values
  21      def read_attribute(attr_name)
  22        value = super(attr_name)
  23        value.is_a?(String) ? value.strip : value
  24      end
  25  
  26      class << self # Class methods
  27        
  28        private
  29          # allow for find_by and such to work with uppercase attributes
  30          # find_by_name => find_by_NAME
  31          # find_by_dob_and_height => find_by_DOB_and_HEIGHT
  32          def extract_attribute_names_from_match(match)
  33            match.captures.last.split('_and_').map { |name| name.upcase }
  34          end
  35      end
  36    end
  37  end


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

   1  
   2  class MyModel < ActiveRecord::MyCustomARClass
   3    # ...
   4  end

Don't reload class in Rails' development environment

Override the reloadable? method in a class to keep Rails dev environment from reloading it. Use this if you're getting "constant uninitialized" on a custom class.

   1  
   2  def self.reloadable?
   3    false
   4  end

Redefine a Rake Task

Some code to help in completely redefining a Rake task

   1  
   2  module Rake
   3    module TaskManager
   4      def redefine_task(task_class, args, &block)
   5        task_name, deps = resolve_args(args)
   6        task_name = task_class.scope_name(@scope, task_name)
   7        deps = [deps] unless deps.respond_to?(:to_ary)
   8        deps = deps.collect {|d| d.to_s }
   9        task = @tasks[task_name.to_s] = task_class.new(task_name, self)
  10        task.application = self
  11        task.add_comment(@last_comment)
  12        @last_comment = nil
  13        task.enhance(deps, &block)
  14        task
  15      end
  16    end
  17    class Task
  18      class << self
  19        def redefine_task(args, &block)
  20          Rake.application.redefine_task(self, args, &block)
  21        end
  22      end
  23    end
  24  end
  25  
  26  def redefine_task(args, &block)
  27    Rake::Task.redefine_task(args, &block)
  28  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.

   1  
   2  module Rake
   3    module TaskManager
   4      def redefine_task(task_class, args, &block)
   5        task_name, deps = resolve_args(args)
   6        task_name = task_class.scope_name(@scope, task_name)
   7        deps = [deps] unless deps.respond_to?(:to_ary)
   8        deps = deps.collect {|d| d.to_s }
   9        task = @tasks[task_name.to_s] = task_class.new(task_name, self)
  10        task.application = self
  11        task.add_comment(@last_comment)
  12        @last_comment = nil
  13        task.enhance(deps, &block)
  14        task
  15      end
  16    end
  17    class Task
  18      class << self
  19        def redefine_task(args, &block)
  20          Rake.application.redefine_task(self, args, &block)
  21        end
  22      end
  23    end
  24  end
  25  
  26  def redefine_task(args, &block)
  27    Rake::Task.redefine_task(args, &block)
  28  end
  29  
  30  namespace :db do
  31    namespace :test do
  32  
  33      desc 'Prepare the test database and migrate schema'
  34      redefine_task :prepare => :environment do
  35        Rake::Task['db:test:migrate_schema'].invoke
  36      end
  37  
  38      desc 'Use the migrations to create the test database'
  39      task :migrate_schema => 'db:test:purge' do
  40        ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
  41        ActiveRecord::Migrator.migrate("db/migrate/")
  42      end
  43    
  44    end
  45  end
« Newer Snippets
Older Snippets »
Showing 1-8 of 8 total  RSS