Recent additions

edit delete favorite
Posted by eric on Sep 02, 2009
put a single name string into namer like namer("Dr. Billy Bob von Doom III") and it will parse it.
PREFIXES = %w{mrs ms miss mr dr prof}
SUFFIXES = %w{jr sr ii iii iv v vi vii viii ix x phd pharmd dds md}
LAST_NAME_PARTICLES = %w{da dal de del der di e la le san st ste van vel von y zu}

def namer(name)
  # if a comma exists, pivot on it
  return '' if name.nil?
  name = name.downcase.split(',').reverse.join(' ').strip
  name.gsub!(/[^\s\w-]/, '')
  parts = name.split(/\s+/)
  
  # :middle=>'',
  full_name = {:last=>'', :first=>'', :pre=>'', :suf=>''}
  if parts.length == 1
    full_name[:last] = parts[0].capitalize
    return full_name
  end
  
  # check if first is a prefix. if so, take it off
  if PREFIXES.include?(parts[0])
    full_name[:pre] = parts.shift.capitalize
  end
  
  # iterate from end, stripping off any suffixes found as a string
  suffixes = []
  while SUFFIXES.include?(parts.last)
    suffixes << parts.pop.upcase
  end
  full_name[:suf] = suffixes.reverse * ' '
  
  # find first last name particle or last remaining name
  ln_pos = 0
  parts.each{|part|
    break if LAST_NAME_PARTICLES.include?(part)
    ln_pos += 1
  }
  
  unless ln_pos == parts.length
    full_name[:first] = parts[0...ln_pos].collect{|x|x.capitalize} * ' '
    parts.last.capitalize!
    full_name[:last] = parts[ln_pos..parts.length] * ' '
  else
    last = parts.pop
    return full_name unless last
    full_name[:last] = last.capitalize
    full_name[:first] = parts.collect{|x|x.capitalize} * ' '
  end
  
  full_name
end
 
edit delete favorite
Posted by danielbalieiro on May 28, 2009
Dúvida sobre Timeout:
Eu coloco dentro de application_controller.rb:
################
 before_filter :session_expiry, :except => [:login, :logout]

 before_filter :update_activity_time, :except => [:login, :logout]

 def session_expiry
   @time_left = (session[:expires_at] - Time.now).to_i
   unless @time_left > 0
     reset_session
     flash[:error] = 'Sua sessão expirou. Favor entrar novamente.'
     redirect_to :controller => 'login', :action => 'login'
   end
 end

 def update_activity_time
   session[:expires_at] = 60.minutes.from_now
 end
################

Assim eu coloquei para 60 minutos e a cada mudança de link a variável
é verificada se passou do tempo, senão é setada para o momento atual.


E no meu login_controller.rb após ser autenticado coloco a linha:
################
     update_activity_time
################
 
edit delete favorite
Posted by eric on Apr 27, 2009
These are two Rails helpers that could be very useful when injecting new instance methods in a class. underscore and classify
'MyClassName'.underscore => my_class_name
cool_articles".classify => CoolArticles
 
edit delete favorite
Posted by eric on Apr 23, 2009
require 'fileutils'

module Daemon
  WorkingDirectory = File.join(File.dirname(__FILE__), '..')

  class Base
    def self.pid_fn
      File.join(WorkingDirectory, "log", "#{name}.pid")
    end
    
    def self.daemonize
      Controller.daemonize(self)
    end
  end
  
  module PidFile
    def self.store(daemon, pid)
      File.open(daemon.pid_fn, 'w') {|f| f << pid}
    end
    
    def self.recall(daemon)
      IO.read(daemon.pid_fn).to_i rescue nil
    end
  end
  
  module Controller
    def self.daemonize(daemon)
      case !ARGV.empty? && ARGV[0]
      when 'start'
        start(daemon)
      when 'stop'
        stop(daemon)
      when 'restart'
        stop(daemon)
        start(daemon)
      else
        puts "Invalid command. Please specify start, stop or restart."
        exit
      end
    end
    
    def self.start(daemon)
      fork do
        Process.setsid
        exit if fork
        PidFile.store(daemon, Process.pid)
        Dir.chdir WorkingDirectory
        File.umask 0000
        STDIN.reopen "/dev/null"
        #STDOUT.reopen "/dev/null", "a"
        STDERR.reopen STDOUT
        trap("TERM") {daemon.stop; exit}
        daemon.start
      end
    end
  
    def self.stop(daemon)
      if !File.file?(daemon.pid_fn)
        puts "Pid file not found. Is the daemon started?"
        exit
      end
      pid = PidFile.recall(daemon)
      FileUtils.rm(daemon.pid_fn)
      pid && Process.kill("TERM", pid)
    end
  end
end
 
edit delete favorite
Posted by juanwalker on Feb 16, 2009
probandola
 
edit delete favorite
Posted by jaduks on Jan 07, 2009
Ways to delete blank lines (in vi,using sed,awk,grep)
In vi , escape mode type

:g/^$/ d

to delete all the blank lines.

Other alternatives:

$ grep -v '^$' file
$ grep '.' file
$ sed '/^$/d' file
$ sed -n '/^$/!p' file
$ awk NF file
$ awk '/./' file
sed, bash, awk, vi
 
edit delete favorite
Posted by jimbojw on Jul 18, 2008
Code to embed a Google Calendar in any page. Replace "GOOGLE_EMAIL_ADDRESS" in the src attribute with the chosen user. Because this is an iframe, there's no need to fork over your password to the party doing the embedding.
<iframe src="http://www.google.com/calendar/embed?height=600&wkst=1&bgcolor=%23FFFFFF&src=GOOGLE_EMAIL_ADDRESS%40gmail.com&color=%232952A3&ctz=America%2FNew_York" style=" border-width:0 " width="800" height="600" frameborder="0" scrolling="no"></iframe>
 
edit delete favorite
Posted by snipsniper on Jan 30, 2008
Ruby uses the same strftime options as PHP.
Us as so:
irb: order.shipped_at.strftime("%Y-%m-%d %I:%M")
=> 2006-03-13 02:55
%a - abbreviated weekday name according to the current locale
%A - full weekday name according to the current locale
%b - abbreviated month name according to the current locale
%B - full month name according to the current locale
%c - preferred date and time representation for the current locale
%C - century number (the year divided by 100 and truncated to an integer,
   range 00 to 99)
%d - day of the month as a decimal number (range 01 to 31)
%D - same as %m/%d/%y
%e - day of the month as a decimal number, a single digit is preceded by
   a space (range ' 1' to '31')
%g - like %G, but without the century.
%G - The 4-digit year corresponding to the ISO week number (see %V).
   This has the same format and value as %Y, except that if the ISO week
   number to the previous or next year, that year is used instead.
%h - same as %b
%H - hour as a decimal number using a 24-hour clock (range 00 to 23)
%I - hour as a decimal number using a 12-hour clock (range 01 to 12)
%j - day of the year as a decimal number (range 001 to 366)
%m - month as a decimal number (range 01 to 12)
%M - minute as a decimal number
%n - newline character
%p - either `am' or `pm' according to the given time value, or the
   corresponding strings for the current locale
%r - time in a.m. and p.m. notation
%R - time in 24 hour notation
%S - second as a decimal number
%t - tab character
%T - current time, equal to %H:%M:%S
%u - weekday as a decimal number [1,7], with 1 representing Monday
%U - week number of the current year as a decimal number, starting with
   the first Sunday as the first day of the first week
%V - The ISO 8601:1988 week number of the current year as a decimal
   number, range 01 to 53, where week 1 is the first week that has at
   least 4 days in the current year, and with Monday as the first day
   of the week. (Use %G or %g for the year component that corresponds
    to the week number for the specified timestamp.)
%W - week number of the current year as a decimal number, starting with
   the first Monday as the first day of the first week
%w - day of the week as a decimal, Sunday being 0
%x - preferred date representation for the current locale
   without the time
%X - preferred time representation for the current locale
   without the date
%y - year as a decimal number without a century (range 00 to 99)
%Y - year as a decimal number including the century
%Z or %z - time zone or name or abbreviation
%% - a literal `%' character
 
Please submit any bugs/features and report abuse. Thanks!
Spacer
Spacer
Spacer
Top Tags
Spacer