Recent additions

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.
 
edit delete favorite
Posted by snipsniper on Nov 29, 2007
Common File methods and modes.
File.join(p1, p2, ... pN)           => "p1/p2/.../pN" platform independent paths
File.new(path, modestring="r")      => file
File.new(path, modenum [, permnum]) => file
IO.readlines(path)                  => array
File.open(fileName, aModeString="r") {|file| block}
File.open(fileName [, aModeNum [, aPermNum ]]) {|file| block}
IO.foreach(path, sepstring=$/) {|line| block}

# Mode Strings
r   # Read-only, starts at beginning of file (default mode).
r+  # Read-write, starts at beginning of file.
w   # Write-only, truncates existing file to zero length or creates a new file for writing.
w+  # Read-write, truncates existing file to zero length or creates a new file for reading and writing.
a   # Write-only, starts at end of file if file exists, otherwise creates a new file for writing.
a+  # Read-write, starts at end of file if file exists, otherwise creates a new file for reading and writing.
b   # (DOS/Windows only) Binary file mode (may appear with any of the key letters listed above).
 
edit delete favorite
Posted by snipsniper on Nov 29, 2007
In all of the %() cases below, you may use any matching characters or any single character for delimiters. %[], %!!, %@@, etc.
'no interpolation'
"#{interpolation}, and backslashes\n"
%q(no interpolation)
%Q(interpolation and backslashes)
%(interpolation and backslashes)
`echo command interpretation with interpolation and backslashes`
%x(echo command interpretation with interpolation and backslashes)

# Backslashes
\t (tab), \n (newline), \r (carriage return), \f (form feed),
\b (backspace), \a (bell), \e (escape), \s (whitespace), \nnn (octal),
\xnn (hexadecimal), \cx (control x), \C-x (control x), \M-x (meta x),
\M-\C-x (meta control x)

# Here Docs
<<identifier   - interpolated, goes until identifier
<<"identifier" - same thing
<<'identifier' - no interpolation
<<-identifier  - you can indent the identifier by using "-" in front
 
edit delete favorite
Posted by eric on Nov 29, 2007
Range [www.ruby-doc.org] cheat-sheet for Ruby.
1..5             => [0, 1, 2, 3, 4, 5]
1...5            => [0, 1, 2, 3, 4]
'a'..'d'         => ['a', 'b', 'c', 'd']
'a'...'d'        => ['a', 'b', 'c']
(1..10)  === 10  => true
(1...10) === 10  => false
(1..10)  === 15  => false

while gets # prints lines starting at 'start' and ending at 'end'
  print if /start/../end/
end

# represent a string of 'x's as a Range
class Xs
  include Comparable
  def initialize(n)
    @length = n
  end
  def inspect
    'x' * @length
  end
  # override the following for range utility
  def succ
    Xs.new(@length + 1)
  end
  def <=>(other)
    @length <=> other.length
  end
end
r = Xs.new(3)..Xs.new(6)   #=> xxx..xxxxxx
r.to_a                     #=> [xxx, xxxx, xxxxx, xxxxxx]
r.member?(Xs.new(5))       #=> true

# Ranges can use === comparisons, thus can use case statements
case 12
when 1..10  then   puts "less than 10"
when 10..20 then   puts "between 10 and 20"
when 20..30 then   puts "greater than 20"
end
# outputs => between 10 and 20
 
edit delete favorite
Posted by eric on Nov 28, 2007
Regular expression cheat-sheet for Ruby.
/normal regex/iomx[neus]
%r|alternate form|

# options:

/i         case insensitive
/o         only interpolate #{} blocks once
/m         multiline mode - '.' will match newline
/x         extended mode - whitespace is ignored
/[neus]    encoding: none, EUC, UTF-8, SJIS, respectively

# regex characters:

.          any character except newline
[ ]        any single character of set
[^ ]       any single character NOT of set
*          0 or more previous regular expression
*?         0 or more previous regular expression(non greedy)
+          1 or more previous regular expression
+?         1 or more previous regular expression(non greedy)
?          0 or 1 previous regular expression
|          alternation
( )        grouping regular expressions
^          beginning of a line or string
$          end of a line or string
{m,n}      at least m but most n previous regular expression
{m,n}?     at least m but most n previous regular expression(non greedy)
\A         beginning of a string
\b         backspace(0x08)(inside[]only)
\b         word boundary(outside[]only)
\B         non-word boundary
\d         digit, same as[0-9]
\D         non-digit
\S         non-whitespace character
\s         whitespace character[ \t\n\r\f]
\W         non-word character
\w         word character[0-9A-Za-z_]
\z         end of a string
\Z         end of a string, or before newline at the end
(?# )      comment
(?: )      grouping without backreferences
(?= )      zero-width positive look-ahead assertion
(?! )      zero-width negative look-ahead assertion
(?ix-ix)   turns on/off i/x options, localized in group if any.
(?ix-ix: ) turns on/off i/x options, localized in non-capturing group.

# special character classes:

[:alnum:]   alpha-numeric characters
[:alpha:]   alphabetic characters
[:blank:]   whitespace - does not include tabs, carriage returns, etc
[:cntrl:]   control characters
[:digit:]   decimal digits
[:graph:]   graph characters
[:lower:]   lower case characters
[:print:]   printable characters
[:punct:]   punctuation characters
[:space:]   whitespace, including tabs, carriage returns, etc
[:upper:]   upper case characters
[:xdigit:]  hexadecimal digits
 
edit delete favorite
Posted by eric on Nov 28, 2007
Here is a Ruby program that I use to search my IMAP mailbox with combinations of search criteria. It is a mixture of several different Ruby-based approaches I found on the Internet for searching email systems.

Note that you don't need all the comments at the front as I've shown. It's just that I can't remember all the crazy flags that can be used, and at this time I'm not going to take the time to write a better mail system interface, although IMHO a better interface is surely needed.

Without any further ado, here is my Ruby source code that lets you search your email with powerful options/combinations:
require 'net/imap'

# mostly written by Al Alexander, http://DevDaily.com
# (okay, okay, i copied a lot of it and glued it together)

# ==========
# IMAP FLAGS
# ==========
# BEFORE <date>:  8-Aug-2002.
# BODY <string>:
# CC <string>:
# FROM <string>:
# NEW:  messages with the \Recent, but not the \Seen, flag set.
# NOT <search-key>:
# OR <search-key> <search-key>: "or" two search keys together.
# ON <date>:
# SINCE <date>:
# SUBJECT <string>:
# TO <string>:

# ===============
# ENVELOPE FIELDS
# ===============
# date:
# subject:
# from:     an array of Net::IMAP::Address
# sender:   an array of Net::IMAP::Address
# reply_to: an array of Net::IMAP::Address
# to:       an array of Net::IMAP::Address
# cc:       an array of Net::IMAP::Address
# bcc:      an array of Net::IMAP::Address

# ==============
# ADDRESS FIELDS
# ==============

# name:
# route:
# mailbox:
# host:

server = "MY-MAILSERVER"    # change this for your system
user = "MY-USERNAME"        # change this for your system
pass = "MY-PASSWORD"        # change this for your system
#folder = "INBOX.Sent"      # shows how to specify a different folder
folder = "INBOX"

imap = Net::IMAP.new(server)
imap.login(user, pass)
imap.select(folder)

# "SINCE", "1-Apr-2003"
#imap.search(["FROM", "ann", "NOT", "NEW", "SINCE", "1-Apr-2003", 
#             "BODY", "tree"]).each do |msg_id|
#imap.search(["TO", "reggie", "BODY", "vacation"]).each do |msg_id|

imap.search(["FROM", "fred", "BODY", "ssh").each do |msg_id|
  msg = imap.fetch(msg_id, "(UID RFC822.SIZE ENVELOPE BODY[TEXT])")[0]
  body = msg.attr["BODY[TEXT]"]
  puts "#{body}"

  #envelope = msg.attr["ENVELOPE"]
  #uid = msg.attr["UID"]
  #size = msg.attr["RFC822.SIZE"]
  #puts "To: #{to}"

  env = imap.fetch(msg_id, "ENVELOPE")[0].attr["ENVELOPE"]
  puts "#{env.from[0].name}: \t#{env.subject}"
end

imap.logout
imap.disconnect
 
Please submit any bugs/features and report abuse. Thanks!
Spacer
Spacer
Spacer
Top Users
Spacer
Top Tags
Spacer