DEV Community

Cover image for Hey, post a selfie! Show yourself!

Posted on

Hey, post a selfie! Show yourself!


I've seen some interest in a feature within one of my earlier apps called WERQBOOK- a chat app with some simple but really important features like time stamps, real-time updates, and image posting. It's the image posting that sparks the most interest. Rails made it so easy!

Let's get started!

I ran gem install carrierwave fog mini_magick && bundle install to get started. CarrierWave allowed access rails generate uploader Picture to create an image uploader. The images were to be uploaded into user posts, so I ran rails generate migration add_picture_to_microposts picture:string && rails db:migrate to add image strings to the existing schema. The generator added mount_uploader :picture, PictureUploader to the micropost.rb file. Then I needed to update the private micropost_params method in micropost_controller.rb to "permit" :picture.

I added an image_tag to the _micropost_form.html.erb partial to prompt image uploads.

<span class="content">
  <%= micropost.content %>
  <%= image_tag micropost.picture.url if micropost.picture? %>

For some image validation I added a simple method into the picture_uploader.rb file.

def extension_whitelist 
  %w(jpg jpeg gif png) 

I added another validation in micropost.rb through validate :picture_size and a private picture_size method

def picture_size 
  if picture.size > 5.megabytes
    errors.add(:picture, "should be less than 5MB")

Images could be posted of any size, potentially ruining the layout of the application. I found I needed to brew install imagemagick into my development environment. The MiniMagick documentation was pretty good, which I followed to add the following into the picture_uploader.rb file.

include CarrierWave::MiniMagick 
process resize_to_limit: [400, 400]

Finally I updated picture_uploader.rb for production storage with

if Rails.env.production? 
  storage :fog 
  storage :file

That's all folks!

Top comments (0)