Oct 232009
 

Very quick rdebug primer for using the debugger in Mongrel.

<h1>Setting Up your Environment for Debugging</h1>

gem install ruby-debug

If you’re in textmate go to Bundles > Bundle Editor > Edit Snippits… Add a new snippit like so:
[IMAGE:X]

<h1>How to Debug</h1>

1) Set a breakpoint in your code. Do this by typing “debug” followed by tab in TextMate. If setup correctly, TextMate will replace your debug statement with this:

require “rubygems”; require “ruby-debug”; debugger

2) Fire up mongrel (script/server -p 3000)

3) Run your application in the browser. At the breakpoint, Mongrel will stop (this will mean your browser will “hang” while it is loading the page). At this point, you can debug.

Use <strong>p</strong> to see the value of any variable (actually you’ll probably want <strong>pp</strong> for “pretty print”).

Use <strong>c</strong> to <strong>continue</strong> (go back to running code).

Use <strong>l =</strong> to see the line you are on.

Command Alias Usage What it does
help Type ‘help ‘ for help on a specific command
backtrace bt Print the entire stack frame. Each frame is numbered, the most recent frame is 0. frame number can be referred to in the “frame” command;
“up” and “down” add or subtract respectively to frame numbers shown.
The position of the current frame is marked with ->.
break b b[reak] file:line [if expr]
b[reak] class(.|#)method [if expr]
set breakpoint to some position, (optionally) if expr == true
catch cat cat[ch] Intercept when there would otherwise be is no handler for it.
condition Condition breakpoint-number expression Specify breakpoint number N to break only if COND is true.
N is an integer and COND is an expression to be evaluated whenever
breakpoint N is reached. If the empty string is used, the condition is removed.
continue c or cont c [ nnn] run until program ends, hits a breakpoint or reaches line nnn
delete del del [ nnn…] delete some or all breakpoints
disable Disable some things.

A disabled item is not forgotten, but has no effect until reenabled.
Use the “enable” command to have it take effect again.

List of disable subcommands:

disable breakpoints – Disable some breakpoints
disable display – Disable some display expressions when program stops

display disp disp or disp add expression into display expression list (when used with expression); or display expression list when no expression is specified
down down[count] move to lower frame
edit Edit specified file.

With no argument, edits file containing most recent line listed.
Editing targets can also be specified in this:
FILE:LINENUM, to edit at that line in that file,

enable Enable some things.
This is used to cancel the effect of the “disable” command.

List of enable subcommands:

enable breakpoints – Enable specified breakpoints
enable display – Enable some expressions to be displayed when program stops
eval e (also alias for p) e evaluate expression and print its value. * NOTE – to turn on autoeval, use ‘set autoeval’
exit see quit
finish fin fin [frame-number] Execute until selected stack frame returns. If no frame number is given, we run until the currently selected frame
returns. The currently selected frame starts out the most-recent
frame or 0 if no frame positioning (e.g “up”, “down” or “frame”) has
been performed. If a frame number is given we run until that frame
returns.
frame f f frame-number [thread thread-number] Move the current frame to the specified frame number.

A negative number indicates position from the other end. So
‘frame -1’ moves to the oldest frame, and ‘frame 0’ moves to
the newest frame.

Without an argument, the command prints the current stack
frame. Since the current position is redisplayed, it may trigger a
resyncronization if there is a front end also watching over
things.

If a thread number is given then we set the context for evaluating
expressions to that frame of that thread.

help help Type ‘help ‘ for help on a specific command.
info Generic command for showing things about the program being debugged.

List of info subcommands:

info args – Argument variables of current stack frame
info breakpoints – Status of user-settable breakpoints
info catch – Exceptions that can be caught in the current stack frame
info display – Expressions to display when program stops
info file – Info about a particular file read in
info files – File names and timestamps of files read in
info global_variables – Global variables
info instance_variables – Instance variables of the current stack frame
info line – Line number and file name of current position in source file
info locals – Local variables of the current stack frame
info program – Execution status of the program
info stack – Backtrace of the stack
info thread – List info about thread NUM
info threads – information of currently-known threads
info variables – Local and instance variables of the current stack frame
irb starts an Interactive Ruby (IRB) session.
list l l or l – or l = or l nn-mm l
list forward
l –
list backward
l =
list current line
l nn-mm
list given lines

NOTE – to turn on autolist, use ‘set autolist’

method m m i
m iv
m
show methods of object (m i); show instance variables of object (m iv); show instance methods of class or module
next n[+-]?[ nnn] step over once or nnn times, ‘+’ forces to move to another line. ‘-‘ is the opposite of ‘+’ and disables the force_stepping setting.
p see eval
pp pp expression evaluate expression and pretty-print its value
ps ps expression evaluate expression, an array, sort, and columnize its value
putl putl expression evaluate expression, an array, and columnize its value
quit exit q [unconditionally] Normally we prompt before exiting. However if the parameter
“unconditionally” is given, we stop without asking further questions
reload r forces source code reloading
restart restart|R [args] Restart the program. This is is a re-exec – all debugger state
is lost. If command arguments are passed those are used.
save save [FILE] Saves current debugger state to FILE as a script file.
This includes breakpoints, catchpoints, display expressions and some settings.
If no filename is given, we will fabricate one.

Use the ‘source’ command in another debug session to restore them.

set Modifies parts of the ruby-debug environment. Boolean values take
on, off, 1 or 0.
You can see these environment settings with the “show” command.


List of set subcommands:

set annotate – Set annotation level
set args – Set argument list to give program being debugged when it is started
set autoeval – Evaluate every unrecognized command
set autolist – Execute ‘list’ command on every breakpoint
set autoirb – Invoke IRB on every stop
set autoreload – Reload source code when changed
set basename – Report file basename only showing file names
set callstyle – Set how you want call parameters displayed
set debuggertesting – Used when testing the debugger
set forcestep – Make sure ‘next/step’ commands always move to a new line
set fullpath – Display full file names in frames
set history – Generic command for setting command history parameters
set keep-frame-bindings – Save frame binding on each call
set linetrace+ – Set line execution tracing to show different lines
set linetrace – Set line execution tracing
set listsize – Set number of source lines to list by default
set trace – Display stack trace when ‘eval’ raises exception
set width – Number of characters the debugger thinks are in a line

show Generic command for showing things about the debugger.


List of show subcommands:

show annotate – Show annotation level
show args – Show argument list to give program being debugged when it is started
show autoeval – Show if unrecognized command are evaluated
show autolist – Show if ‘list’ commands is run on breakpoints
show autoirb – Show if IRB is invoked on debugger stops
show autoreload – Show if source code is reloaded when changed
show basename – Show if basename used in reporting files
show callstyle – Show paramater style used showing call frames
show commands – Show the history of commands you typed
show forcestep – Show if sure ‘next/step’ forces move to a new line
show fullpath – Show if full file names are displayed in frames
show history – Generic command for showing command history parameters
show keep-frame-bindings – Save frame binding on each call
show linetrace – Show line execution tracing
show linetrace+ – Show if consecutive lines should be different are shown in tracing
show listsize – Show number of source lines to list by default
show port – Show server port
show post-mortem – Show whether we go into post-mortem debugging on an uncaught exception
show trace – Show if a stack trace is displayed when ‘eval’ raises exception
show version – Show what version of the debugger this is
show width – Show the number of characters the debugger thinks are in a line

source source FILE executes a file containing debugger commands
step s[+-]?[ nnn] step (into methods) once or nnn times; ‘+’ forces to move to another line.; ‘-‘ is the opposite of ‘+’ and disables the force_stepping setting.
thread h[read] l[ist]list all threads

th[read] stop stop thread nnn

th[read] resume resume thread nnn

th[read] [sw[itch]] switch thread context to nnn

th[read] [cur[rent]]show current thread

tmate tm tm n opens a current file in TextMate. It uses n-th frame if arg (n) is specifed.
trace tr[ace] (on|off)set trace mode of current thread
tr[ace] (on|off) allset trace mode of all threads
tr[ace] var(iable) VARNAME [stop|nostop]set trace variable on VARNAME
undisplay undisp[ nnn] Cancel some expressions to be displayed when program stops.
Arguments are the code numbers of the expressions to stop displaying.
No argument means cancel all automatic-display expressions.
“delete display” has the same effect as this command.
Do “info display” to see current list of code numbers.
up up[count] move to higher frame
var v v[ar] cl[ass] show class variables of self

v[ar] c[onst] show constants of object

v[ar] g[lobal]show global variables

v[ar] i[nstance] show instance variables of object

v[ar] l[ocal]show local variables

where alias for backtrace (see backtrace)
 Posted by at 3:19 pm  Tagged with:
Oct 112009
 

Web Developer — adds a robust set of tools to peek under the hood. Adds a toolbar to your windows to let you do things like disable Javascript, cookies, css, see field names for a form on the page etc.

Firebug – the king of web developer firefox plug-ins.

View Source Chart

Ever find the “View Source” that Firefox provides a little hard to read? The windows opens with a raw display of the HTML as rendered by the page, but looking at raw HTML can be straining to the eyes if not downright dizzying. When working in code editors, the editor typically does syntax coloring. Here’s a great Firefox add-on which adds a “View Source Chart” to every page so that your view source comes out nicely formatted and colored:

 Posted by at 6:17 pm
Oct 072009
 

All programming languages work this way, but still it is nice to remember that Ruby does this.

>> n = nil
=> nil
>> x # x is undefined, just showing you that
NameError: undefined local variable or method `x’ for #
from (irb):6
>> (x || n.nil?) # x evaluates first, but since it’s undefined raises error
NameError: undefined local variable or method `x’ for #
from (irb):7
>> n.nil? || x # n.nil? is true, and so x never gets evaluated, thus not raising the error
=> true

The same behavior works for the && (and) operator, of course it stops if it finds a false where as the || (or) operator stops when it finds a true (as you would expect).

>> ! @var.nil? && @var.a == “xyz”
=> false
>> @var.a == “xyz” && ! @var.nil?
NoMethodError: You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.a
from (irb):13

So, this is most often useful for me when a variable that I need to check an attribute of might or might not be instantiated.

<% if ! @var.nil? && @var.a == "xyz" %>
The a attribute of your @var is xyz
<% end %>
 Posted by at 1:25 pm
Oct 072009
 

Two of the interesting startups presented tonight at NY Tech meetup underscore one of the crucial facets of the tech industry today: In terms of what will be successful, no one really knows what is going to happen next.

Unless something is really the next Facebook or Twitter, it is going to have to piggyback on existing tools or data sources.

Tagnic (playtagnic.com) is an interesting twist on an old theme. Twitter already lets you mention other twitter users (known as an @ reply), but Tagnic allows you to attach ideas to that person – like rockstar, sexy, or nerd. You can wish someone happy birthday, or good luck. You don’t need to sign up for this service separately from Twitter; it is a Twitter application. You also don’t need to learn anything very special to use it. You just use a plus symbol (+) followed by the tag you are tagging the person with.

If you receive enough tags attached to your name, you get a “badge” from Tagnic, kind of like a scout badge.

In my opinion this is noteworthy but probably not going all that far. Interesting? Yes. Revolutionary? Hardly. One of the criticisms that was mentioned at the meetup was what happens if people tag bad things about you. At best, this could be a friendly jest. At worst, this could be a visceral attack on another individual. Like Twitter mentions, there’s actually no way to erase what other people say about you in a tag. The company had no official response to this social downside.

Something heard not too often in a tech industry sense, when asked “What’s your revenue model?” founder Adam Simon replies bluntly: “We have none.” By the sheer gusto of his response, this statement is met by the 500+ person audience with rapturous applause.

* * *

AnyClip

Only in the tech industry could a business come so far along with a technical platform whose very premise exists on questionable legal grounds. Anyclip (anyclip.com) has created an interesting and innovative technology for movie buffs: a transcribed and time-coded collection of every line of dialog in big production movies.

Aaron Cohen, CEO and Co-Founder, types “stay puff marshmellow man” into the search engine and the iconic scene from Ghost Busters of the giant marshmallow man destroying New York comes right up.

The transcripts are time-coded to the exact point in the movie where the dialog (or thing) appears, so you get a clip of that very scene. Pretty cool, if the idea works and flies.

Personally, I’m not certain about the technology. In his demo Cohen asks the audience for any term. Someone shouts out “bicycling.” When he searched for this, several movie clips with no bicycles come up. While there could be various reasons for this glitch, it seems that the data set being search is large and refinement of the query is a precise science that they have yet to master. (I also searched myself for “I’ll have what she’s having” and couldn’t find the famous scene that takes place in Katz’s deli from When Harry Met Sally.) While not a fatal flaw, it seems like the engine should know based on relevance and popularity what you are probably searching for.

The main elephant in the room for Anyclip is: Do they have the rights to show these clips? Well, er, actually no. As of now they have no deals with the big 6 movie studies (which control 88% of the US Marketshare 1)

Anyclip claims their lawyers say that they can use up to four minutes of a clip for promotional use. Nevertheless, official studio sanctioning is their plan. In september, they told Jason Kincaid of TechCrunch: “I’m not that interested in having tons of content that they dont want us to have. We can’t build a business on the backs of their content illegally and hope it works. Over time we will get it all.” 2

References
1. boxofficemojo.com
2. TechCrunch

 Posted by at 12:00 pm
Oct 062009
 

In trying to write code to give me the full name of “next” month (in my case, November, as today is October 6), I just stumbled across this interesting little Rubyism. Indeed, as you’ll see below, I’m simply trying to add one thing to another thing. In other languages and what we were taught in math, the order of these two things don’t matter. You’d think a + b is the same as b + a. In general it is, but here’s an interesting edge case involving manipulating dates.

Take our a + b example above. As an object-based language Ruby is going to call the plus method on a object, passing it the parameter b. In doing so, it will try to coerce that parameter to something which can be added (as in the plus method).

1.month returns a number, or FixNum more precisely, which is normally happy to be cast (coerced) into a Time object.

But a Time can’t be cast as a Fixnum (why I don’t know and probably shouldn’t ask). So you get behavior like this:

>> (1.month + Time.now).strftime(“%B”)
TypeError: Time can’t be coerced into Fixnum
from /some/path/to/my/project/vendor/rails/activesupport/lib/active_support/duration.rb:20:in `+’
from /some/path/to/my/project/vendor/rails/activesupport/lib/active_support/duration.rb:20:in `+’
from (irb):14

Time.now is a time object, and the plus method on the fixnum that evaluates from 1.month doesn’t know what to do with a time object.

But, switch to b + a, and it works:

>> (Time.now + 1.month).strftime(“%B”)
=> “November”

This is because the time object’s plus method knows what to do with a fixnum – treat it as the number of seconds to add to the time.

For completion sake, let’s make sure everything I said up top is actually correct…

?> Time.now.class
=> Time
>> 1.month.class
=> Fixnum
>> (Time.now + 1.month).class
=> Time
 Posted by at 4:19 pm