Is it possible to get the distance a ray travels inside an object with cycles material nodes?

Then map it to a 0-1 range to create a map:

E.g. to adjust the color of a Glass node to make it more transparent where there is less volume between the camera and light:

How can I do this?
The example images above were rendered with the Layer weight node. This only works on spheres.