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

« Newer Snippets
Older Snippets »
Showing 1-10 of 14 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?}

Mark directories to be deleted based on their date-stamp

This Ruby code selects file directories which are older than a certain date and outputs an XML file naming all the directories to be removed. It does this by reading a directory listing formatted within the XML file 'dir.xml', all directories are named by a date-stamp, which is used to determine if the directory should be removed.

This example is used to maintain the webcamera (named 'pear') which saves it's images to a date-stamped directory daily. Any directory which is older than 14 days will be marked for deletion.

  def directory_housekeeping()
    lifespan = 14
    format_mask = 'm_d_y'
    separator = format_mask.match(/[\_*\-]/).to_s
    
    earliest_date = Time.now + (60 * 60 * 24) * -lifespan
    cut_off_date = Date.new(y=earliest_date.year,m=earliest_date.month,d=earliest_date.day)
        
    a_format = Array.new
    a_format[0] = format_mask.match(/^[y,m,d]*/).to_s
    a_format[1] = format_mask.match(separator + '[y,m,d]*').to_s.gsub(separator,'')
    a_format[2] = format_mask.match('[y,m,d]$').to_s
    
    file = File.new('../housekeeping/webcam_pear/dir.xml')
    ddoc = REXML::Document.new(file)
    file.close
    
    file_delete = File.new('../housekeeping/webcam_pear/files2delete.xml', 'w')
    doc_delete = Document.new()
    doc_delete.add_element('files')
    
    ddoc.root.elements.each('file') do |file_node|
      sfile = file_node.text
      idate = Array.new
      idate[0] = sfile.match(/^\d*/).to_s.to_i
      idate[1] = sfile.match(/\_\d*/).to_s.gsub(separator,'').to_i
      idate[2] = sfile.match(/\_\d*\d$/).to_s.gsub(separator,'').to_i

      h = Hash.new
      0.upto(2) {|i| h[a_format[i]] = idate[i]}

      file_date = Date.new(y=h['y'], m=h['m'], d=h['d'])

      if file_date < cut_off_date
        o_file2delete = Element.new('file')
        o_file2delete.text = file_date.strftime(dformat)
        doc_delete.root.add_element o_file2delete
      end
    end
    file_delete.puts doc_delete
  end



file: dir.xml
<dir>
  <file>11_4_2007</file>
  <file>11_5_2007</file>
  <file>11_6_2007</file>
  <file>11_7_2007</file>
  <file>11_8_2007</file>
  <file>11_9_2007</file>
  <file>12_10_2007</file>
  <file>12_11_2007</file>
  <file>12_1_2007</file>
  <file>12_12_2007</file>
  <file>12_13_2007</file>
  <file>12_14_2007</file>
  <file>12_15_2007</file>
  <file>12_16_2007</file>
  <file>12_17_2007</file>
  <file>12_18_2007</file>
  <file>12_19_2007</file>
  <file>12_20_2007</file>
  <file>12_21_2007</file>
  <file>12_2_2007</file>
  <file>12_22_2007</file>
  <file>12_23_2007</file>
  <file>12_24_2007</file>
  <file>12_25_2007</file>
  <file>12_26_2007</file>
  <file>12_27_2007</file>
  <file>12_28_2007</file>
  <file>12_3_2007</file>
  <file>12_4_2007</file>
  <file>12_5_2007</file>
  <file>12_6_2007</file>
  <file>12_7_2007</file>
  <file>12_8_2007</file>
  <file>12_9_2007</file>
 </dir>

file: files2delete.xml
<files>
  <file>11_4_2007</file>
  <file>11_5_2007</file>
  <file>11_6_2007</file>
  <file>11_7_2007</file>
  <file>11_8_2007</file>
  <file>11_9_2007</file>
  <file>12_10_2007</file>
  <file>12_11_2007</file>
  <file>12_1_2007</file>
  <file>12_12_2007</file>
  <file>12_13_2007</file>
  <file>12_14_2007</file>
  <file>12_15_2007</file>
  <file>12_2_2007</file>
  <file>12_3_2007</file>
  <file>12_4_2007</file>
  <file>12_5_2007</file>
  <file>12_6_2007</file>
  <file>12_7_2007</file>
  <file>12_8_2007</file>
  <file>12_9_2007</file>
 </files>

Using Regular Expressions to validate a fixed length numerical string.

Using Ruby and Regular Sxpressions, this code successfully validates a string if it contains exactly 3 numbers.

a = '547'
/^\d\d\d$/ ~= a

Using Regular Expressions to validate a numerical string.

Using Ruby and Regular Expressions, this code validates a string for numbers only. If the string variable contains only numbers then 0 will be returned otherwise nil.

a = '134323'
/^[0-9]*$/ =~ a
#result returns 0, indicating success

Rails URL Validation

No regexes, allows URLs with ports or IPs. Inspiration from here

  validates_each :href, :on => :create do |record, attr, value|
    begin
      uri = URI.parse(value)
      if uri.class != URI::HTTP
        record.errors.add(attr, 'Only HTTP protocol addresses can be used')
      end
    rescue URI::InvalidURIError
      record.errors.add(attr, 'The format of the url is not valid.')
    end
  end

validate parent model

Validate a parent model in child model
based on a post at http://www.railsweenie.com/forums/1/topics/439
question : can this be improvised?

Book (parent)
class Book < ActiveRecord::Base
  has_many :pages
end


Pages (children)
class Pages < ActiveRecord::Base
  belongs_to :book
  
  validates_presence_of :page_id # this is not enough, anything can go in this field

  # we check if the parent object is valid or not
  validate do |page|
   if page.blank?
     unless page.book(true)
       errors.add(:page_id, "must be a valid Book id")
     end
   end
  end

end

Snazzy url fixer using Ruby's super method

Within the body of a method, a call to super acts just like a call to that original method, except that the search for a method body starts in the superclass of the object that was found to contain the original method.

  def url=(addr)
    super (addr.blank? || addr.starts_with?('http')) ? addr : "http://#{addr}"
  end


Validate uniqueness of an id pair

# Prevent user from joining group twice
def validate
	errors.add_to_base("You are already a member of the #{self.group.name} Group") unless Grouping.find(:all, :conditions => {:user_id => self.user_id, :group_id => self.group_id}).blank?
end

Javascript numeric validation

I've seen a lot of takes on numeric validation, and most have serious flaws. For example, (!isNaN) returns inconsistent results and shouldn't be used to verify numericality. This should cover all cases, and supports a decimal point as well as negative numbers.

function isNumeric(value) {
  if (value == null || !value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
  return true;
}


This logic is straight-forward: if the parameter isn't null, convert it to a string and match it against a RegEx to throw out false cases. Otherwise, return true.

Verify Dates in Rails

From http://www.railtie.net/articles/2006/09/07/validate-dates-in-your-models:
>>>

The thing I find really nice is that if you pass it a malformed date, it returns nil. This means, in your model validations, you can add:
require 'chronic'

class Meeting < ActiveRecord::Base

  def validation
    errors.add :meeting_date, 'is not a valid date' if Chronic.parse(meeting_date.to_s).nil?
  end

end

<<<
Other Chronic examples:
>>>
mojombo in #caboose, just released his first version of Chronic, a new Ruby Gem for natural language processing of Dates and Times.
gem install chronic

irb:>
Chronic.parse('tomorrow')
    #=> Mon Aug 28 12:00:00 PDT 2006

Chronic.parse('monday', :context => :past)
    #=> Mon Aug 21 12:00:00 PDT 2006

Chronic.parse('this tuesday 5:00')
    #=> Tue Aug 29 17:00:00 PDT 2006

Chronic.parse('this tuesday 5:00', :ambiguous_time_range => :none)
    #=> Tue Aug 29 05:00:00 PDT 2006

Chronic.parse('may 27th', :now => Time.local(2000, 1, 1))
    #=> Sat May 27 12:00:00 PDT 2000

Chronic.parse('may 27th', :guess => false)
    #=> Sun May 27 00:00:00 PDT 2007..Mon May 28 00:00:00 PDT 2007


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