简体   繁体   中英

Iterate through hash within a hash

I have this hash

"animal_images_attributes"=>{
 "0"=>{
   "image_cache"=>"",
   "image"=>#<ActionDispatch: : Http: : UploadedFile: 0x0000000673efa0@tempfile=#<Tempfile: /tmp/RackMultipart20140930-17710-u3g1hm>,
   @original_filename="bryony_portfolio.png",
   @content_type="image/png",
   @headers="Content-Disposition: form-data; name=\"animal[animal_images_attributes][0][image]\"; filename=\"bryony_portfolio.png\"\r\nContent-Type: image/png\r\n">,
   "_destroy"=>"false"
 },
 "1412109521172"=>{
   "image_cache"=>"",
   "image"=>#<ActionDispatch: : Http: : UploadedFile: 0x0000000673ea78@tempfile=#<Tempfile: /tmp/RackMultipart20140930-17710-1670i9p>,
   @original_filename="vandals_portfolio.png",
   @content_type="image/png",
   @headers="Content-Disposition: form-data; name=\"animal[animal_images_attributes][1412109521172][image]\"; filename=\"vandals_portfolio.png\"\r\nContent-Type: image/png\r\n">,
   "_destroy"=>"false"
  }
 }
}

And I would like to iterate over each image and get the file size for "image", if the file size is over 1mb I would like to have an identifier for the image (key) that says it is over. I have built this so far

class AnimalsController < ApplicationController
before_action :max_file_size, only: [:create]

def max_file_size
image = params[:animal][:animal_images_attributes]

image.each do |k,v|
  img_cache = v["image_cache"]
  img = v["image"]

   if img
     tempfilepath = img.tempfile.path
     file_size = File.size(tempfilepath)
     if file_size > 1.megabytes
       @largeImage = true
    else
       @largeImage = false
     end
  end
end
end 

end

But this is assigning the value true to all images rather than the ones that actually are in the iteration.

If I do

if file_size > 1.megabytes
 ap(file_size)
end

I get this outputted to the console

1718186
1141251

which is right because in my example I added two images over 1MB.

The idea of all this is to basically say for each image that is over 1mb then conditionally add this class:

<%= f.fields_for :animal_images do |build| %>
  <div class="<%= 'large_image' if @largeImage = true %> form-group has-feedback">
<% end %>

这将返回所有超过1 MB的图像。

big_images = images.select(&:image).select { |_k, image| File.size(image["image"].tempfile.path) > 1.megabyte }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM