Recent additions

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
 
edit delete favorite
Posted by snipsniper on Nov 29, 2007
A listing of built-in variable types, pre-defined variables, and constants available in Ruby.
# Variables
$global_variable
@@class_variable
@instance_variable
[OtherClass::]CONSTANT
local_variable

# Pseudo variables
self     the receiver of the current method
nil      the sole instance of the Class NilClass(represents false)
true     the sole instance of the Class TrueClass(typical true value)
false    the sole instance of the Class FalseClass(represents false)
__FILE__ the current source file name.
__LINE__ the current line number in the source file.
__END__  the end of the ruby file, ignore everything after

# Pre-defined variables
$!         The exception information message set by 'raise'.
$@         Array of backtrace of the last exception thrown.
$&         The string matched by the last successful pattern match in this scope.
$`         The string to the left  of the last successful match.
$'         The string to the right of the last successful match.
$+         The last bracket matched by the last successful match.
$1         The Nth group of the last successful match. May be > 1.
$~         The information about the last match in the current scope.
$=         The flag for case insensitive, nil by default.
$/         The input record separator, newline by default.
$\         The output record separator for the print and IO#write. Default is nil.
$,         The output field separator for the print and Array#join.
$;         The default separator for String#split.
$.         The current input line number of the last file that was read.
$<         The virtual concatenation file of the files given on command line.
$>         The default output for print, printf. $stdout by default.
$_         The last input line of string by gets or readline.
$0         Contains the name of the script being executed. May be assignable.
$*         Command line arguments given for the script sans args.
$$         The process number of the Ruby running this script.
$?         The status of the last executed child process.
$:         Load path for scripts and binary modules by load or require.
$"         The array contains the module names loaded by require.
$DEBUG     The status of the -d switch.
$FILENAME  Current input file from $<. Same as $<.filename.
$LOAD_PATH The alias to the $:.
$stderr    The current standard error output.
$stdin     The current standard input.
$stdout    The current standard output.
$VERBOSE   The verbose flag, which is set by the -v switch.
$-0        The alias to $/.
$-a        True if option -a is set. Read-only variable.
$-d        The alias to $DEBUG.
$-F        The alias to $;.
$-i        In in-place-edit mode, this variable holds the extension, otherwise nil.
$-I        The alias to $:.
$-l        True if option -l is set. Read-only variable.
$-p        True if option -p is set. Read-only variable.
$-v        The alias to $VERBOSE.
$-w        True if option -w is set.

# Pre-defined global constants
TRUE              The typical true value.
FALSE             The false itself.
NIL               The nil itself.
STDIN             The standard input. The default value for $stdin.
STDOUT            The standard output. The default value for $stdout.
STDERR            The standard error output. The default value for $stderr.
ENV               The hash contains current environment variables.
ARGF              The alias to the $<.
ARGV              The alias to the $*.
DATA              The file object of the script, pointing just after __END__.
RUBY_VERSION      The ruby version string (VERSION was deprecated).
RUBY_RELEASE_DATE The release date string.
RUBY_PLATFORM     The platform identifier.
 
Please submit any bugs/features and report abuse. Thanks!
Spacer
Spacer
Spacer
Top Tags
Spacer