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

Zeke Sikelianos

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

Rails validation for Phone

  validates_length_of :phone, :is => 10, :message => 'must be 10 digits, excluding special characters such as spaces and dashes. No extension or country code allowed.', :if => Proc.new{|o| !o.phone.blank?}
  validates_length_of :fax, :is => 10, :message => 'must be 10 digits, excluding special characters such as spaces and dashes. No extension or country code allowed.', :if => Proc.new{|o| !o.fax.blank?}

Rename old HTML views for Rails 2

# Snagged from http://softiesonrails.com/2007/7/11/upgrading-your-views-to-rails-2-0
for old in `find app/views -name *.rhtml`; do svn mv $old `dirname $old`/`basename $old .rhtml`.html.erb; done

Crack open Firefox's new Places sqlite database with ActiveRecord

require "rubygems"
require "active_record"
require "active_support"

ActiveRecord::Base.establish_connection(
	:adapter => "sqlite3",
	:database => "places.sqlite"
)

class MozHistoryvisit < ActiveRecord::Base
	belongs_to :place, :class_name => "MozPlaces", :foreign_key => "place_id"
end

class MozPlaces < ActiveRecord::Base
end

p Time.now.yesterday
from = Time.now.yesterday.to_i * 1000000

MozHistoryvisit.find(:all, :conditions => ["visit_date > ?", from]).each do |h|
	place = h.place
	puts place.title
	puts place.url
	puts place.visit_count
	puts
end

Find all rows for a certain day; Count days between two dates

# Find all rows created on a certain day; Rails apparently has a built-in :db string format
self.find(:all, :conditions => ["created_at >= ? AND created_at <= ?", day.beginning_of_day.to_s(:db), day.end_of_day.to_s(:db)])

# Find number of days between two dates
def days_between_dates(first, last)
  (YMD(last) - YMD(first))
end

def YMD(date)
  date.to_date.to_s.gsub("-", "").to_i
end

Sample Controller method for using Nico's Contacts gem

  def import
    begin 
      @sites = {"gmail"  => Contacts::Gmail, "yahoo" => Contacts::Yahoo, "hotmail" => Contacts::Hotmail}
      @contacts = @sites[params[:from]].new(params[:login], params[:password]).contacts
      @users , @no_users = [], []
      @contacts.each do |contact|
          if u = User.find(:first , :conditions => "accounts.email = '#{contact[1]}'" , :include =>[:account])
            @users << u 
          else
            @no_users << {:name => contact[0] , :email => contact[1]}
          end            
      end
      respond_to do |format|
        format.html {render :template => 'shared/_contact_list' , :layout => false}
	format.xml {render :xml => @contacts.to_xml}
      end	  
    end
    rescue  Contacts::AuthenticationError
      respond_to do |format|
        format.html {render :text => "Username and password do not match"}
	     format.xml {head :bad_request , :bad_account_login}
      end
    end 

File extension regex

# returns nil if not found or numerical index if found
"dog.jpg" =~ /.*(jpg|png|gif)$/

validates_format_of :image_url, :with => %r{\.(gif|jpg|png)$}i


Mechanize / Hpricot / Scraping setup

require 'rubygems'
require 'cgi'
require 'open-uri'
require 'hpricot'
require 'mechanize'

agent = WWW::Mechanize.new
doc = Hpricot(agent.get(the_url).parser.to_s)

Rails Regex: Convert spaces to dashes

s.gsub!(/\ +/, '-')

Rails Regex Lookaround

(Snagged from http://www.pivotalblabs.com/articles/2007/09/11/string-split-and-regex-lookarounds)

Ruby supports regular expression quite well, so it's not surprising that one can use a lookaround to match a specific position. That also works really well with String#split, so if one needs to extract the key/value out of a string such as this:

s = "TYPE=Exterior RED=119 GREEN=105 BLUE=88 TABLEREQ=PNTTBL-01 TABLE=Primary w/XL GENERICCLR=Beige GENERICCLRCODE=31"
s.split(/\s(?=[A-Z]*=)/)


Just splitting on "space" won't work because there are spaces inside the values, too ("Primary w/XML"). Simple and useful...
« Newer Snippets
Older Snippets »
Showing 1-10 of 20 total  RSS