I’ve used ruby lambdas a few times, but I have to admit that I never really understood them. However, I’ve now come across a case where I have to figure them out. Here’s what I’ve found:

  • just a function without a name
  • in ruby, they’re objects
  • last expression of a lambda is its return value
  • they take parameters by surrounding them with pipes
  • use curly brackets {} for single line lambdas and do…end for multiline lambdas </ul> Why did I want to use them? I use the paperclip gem to upload images to a webpage. I want to change this webpage so that in addition to image files, it will also accept pdfs. On the webpage, I show a thumbnail of each image. For pdf files, I want to have the thumbnail be a png file. The paperclip gem will allow a lambda with the has_attached_file definition. So this is what I have in my model:

    has_attached_file :drawing, 
                    path: "#{Rails.root}/public/system/:attachment/:id/:style/:filename",
                    url: "/system/:attachment/:id/:style/:filename",
                    styles: (lambda do |attachment| 
                      if File.extname(attachment.original_filename) == '.pdf'
                        { thumbnail: ["240x240>","png"], medium: ["680x680>", "png"] }
                      else
                        { thumbnail: ["240x240>"], medium: ["680x680>"] }
                      end
                    end)
    

</pre>

With this, I can use my regular means of displaying the thumbnails as images. I only have to check if the file is a pdf in the one view I have that displays the original file. On that page, I use this:

<pre class="brush:html">&lt;% if (File.extname("#{@image.drawing_file_name}") == '.pdf') %>

<embed src=<%= "#{@image.drawing.url(:original)}"%> width=<%= @image.width %> height=<%= @image.height %>>

<% else %>

<%= link_to((image_tag @image.drawing.url(:original)), action: 'show', id: @image )%>

<% end %> </pre>