Search code examples
ruby-on-railslink-to

how to use link_to_unless in rails for filetype


Is there any easy way to use link_to_unless to only exclude gifs? Basically, I want the link to be inactive/removed for images uploaded that are gifs.

<span itemprop="photo">
   <%= link_to image_tag(place.image.url(:medium)), place, class: "hover" %>
</span>

I'm using the paperclip gem for S3, this is what I have in my models for which I add images. I do not have a model just for images.

has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }
validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]

Solution

  • You can get the content type through the Attachment#content_type method. You can test if the image is a gif with

    place.image.content_type == 'image/gif'
    

    Hence what you want is

    <span itemprop="photo">
       <%= link_to_unless place.image.content_type == 'image/gif', image_tag(place.image.url(:medium)), place, class: "hover" %>
    </span>
    

    The first argument of link_to_unless just takes a condition. In this case it checks if the image url ends in .gif.

    However, this looks like too much logic for the view. I would recommend putting this in a decorator instead.