How do shaped lights work? I know how to program directional lights, point lights and spot lights.  Sometimes though, people have lights that are shaped - like bars, or even a torus.

How does that work from either a ray based or rasterization perspective?
In a path tracer, when tracing a ray to a light with a shape other than a point ("area light" is the usual terminology), you generally select a random point on the surface of the light. When enough samples are taken, this results in both softer specular highlights and softer shadow penumbras: light will be reflected off a surface from a random distribution of incoming directions, and rays cast towards an area light with an obstruction in the way may or may not intersect the obstruction depending on which point on the light was sampled.

In real time, approximations to area lights are used. This Unreal Engine 4 white paper describes some of the considerations. One possibility is the "representative point" method, which per-pixel selects a point in the light's volume (brightest or nearest) and uses that as though it was a point light. Another option is modifying the roughness that is fed into the specular calculation based on a cone that approximates the area light (in the paper as "Specular D Modification").