I just wrote my first lambda in Ruby and have run into an issue when using it with Rails.
I have a class called Material:
class Material < ApplicationRecord
to_kilobytes = lambda { |bytes| bytes / 1000 }
to_megabytes = lambda { |bytes| bytes / 1000000 }
def size
size = self.attachment_file_size
if size < 999999
to_kilobytes.call(size)
elsif size >= 1000000
to_megabytes.call(size)
end
end
end
I am trying to call this size method on my material object in order to find size conversion rates for files. The attachment_file_size method is provided by the Rubygem Paperclip.
When I try calling the size method on this material object in my show.html.erb file -
<span><%= @material.size %></span>
I am getting the following error.
undefined local variable or method `to_kilobytes' for Material:0x007fc6f6cba2e0
If I move the lambdas inside the size method it works fine. I realize this is a scoping error, I am just confused why these who lambdas are not able to be called on the size method since they are global in the class. Can somebody explain?