Get image dimensions with Paperclip in Rails

Hi, it’s been some time since the last post. Lots of work and excuses.
Today I will present a challenge that I had in a new project. The client wanted the original dimensions when uploading images. So I made a private method to extract it with the help of ImageMagick’s Geometry module.

First, add new columns through a migration:

bundle exec rails g migration AddImageDimensionsToPosts
class AddImageDimensionsToPosts < ActiveRecord::Migration[5.0]
  def up
    add_column :posts, :image_width, :integer
    add_column :posts, :image_height, :integer
  end

  def down
    remove_column :posts, :image_width, :integer
    remove_column :posts, :image_height, :integer
  end
end
bundle exec rails db:migrate

Then implement the method:

class User < ApplicationRecord
  belongs_to :team
  has_attached_file :image, {
    styles: {
      new_thumb: 'x1144',
      new_medium: '1242x',
      web_feed: '600x',
      thumb: '200x'
    }
  }

  before_save :extract_dimensions

  # .....

  private
    def extract_dimensions
    tempfile = self.temp_image_url
    unless tempfile.nil?
      geometry = Paperclip::Geometry.from_file(tempfile.sub('https', 'http'))
      self.image_width = geometry.width.to_i
      self.image_height = geometry.height.to_i
    end
  end
end

As you saw we replaced https with http because it gave problems with Amazon’s AWS security which is being used to save the files.

Next we wanted to update all the users’ images that were already in the system. And as a need we created the following script:

heroku run rails console

def update_posts
  time = Time.now
  posts_count = 0
  posts_total = Post.where(image_width: nil, image_height: nil).count
  Post.where(image_width: nil, image_height: nil).find_each do |post|
    image = post.image(:original)
    geometry = Paperclip::Geometry.from_file(image.sub('https', 'http'))
    post.update_attributes(image_width: geometry.width.to_i, image_height: geometry.height.to_i)
    posts_count = posts_count + 1
    puts "#{posts_count}/#{posts_total}"
  end
  puts"#{Time.now - time}"
end

update_posts

We used the find_each method instead of each, with each all the objects are loaded into memory and find_each loads one by one and in our case was much faster as it did not stress the server.

Uniqueness scope on boolean

Hey, It has been a long time since the last post. I was working in hospitality and running some Java. Now I am employed as a Web Developer.

This week I bring you something  I learned right now.

We are building a Medicine web app. This application consists in medical cases and each case has a bunch of questions and each questions has a bunch of answers, and only one question is correct.
So, in order to the user select only one true answer, I have made a validation with a scope.

# Case Model
class Case < ApplicationRecord
  scope :active, lambda{ |time = Date.today| where("? BETWEEN start_date AND end_date", time) }

  belongs_to :specialty

  has_many :questions, dependent: :destroy
end


# Question model
class Question < ApplicationRecord
  belongs_to :case
  has_many :answers, dependent: :destroy

  has_attached_file :know_more
  do_not_validate_attachment_file_type :know_more
end


#Answer model
class Answer < ApplicationRecord
  belongs_to :question

  validates_uniqueness_of :correct, conditions: -> { where(correct: true) }, scope: :question_id
end

Simple Array Sum

Ruby

n = gets.strip.to_i
arr = gets.strip
arr = arr.split(' ').map(&:to_i)
total = 0
arr.each {|num| total += num}
puts total

C

int main(){
    int n, total; 
    scanf("%d",&n);
    int arr[n];
    for(int i = 0; i < n; i++){
       scanf("%d",&arr[i]);
    }
    for (int i = 0; i < n; i++){
        total += arr[i];
    }
    printf("%d", total);
    return 0;
}

Ruby on Rails 5 API

After using Ruby on Rails 5 I do not want to go back, I’ve fell in love. In my opinion this was one of the best updates in software. My congratulations to the core team and all the contributors.

Bcrypt gem is included and it is not necessary the old manual configuration steps which spares a lot of time and makes us focused on other important things.

In some commands the old rake is gone, such as:

rails db:migrate
rails test

To build the API:

rails new tasks --api

Then you add this code to the Gemfile

gem 'active_model_serializers'

After, you create this file and write the code that follows

config/initializers/active_model_serializers.rb

ActiveModel::Serializer.config.adapter = :json_api

Run this command to update the gems

bundle install

Create both Users and Todos using scaffold

rails generate scaffold User email
rails g scaffold Todo title completed:boolean order:integer category:string user:references

The scaffold option makes a lot of things for us but there is more work to do, some configuration, more code and in my case I added authentication.

The code can be checked in my github through the following link: https://github.com/Adnilson/tasks

Solving Algorithms – Largest prime factor

Today I solved this algorithm that is the third problem in Project Euler.
This still need some improvement, because even when the last prime number is found it still counts and takes a really long time when given big numbers.

require 'prime'

def largestPrime(num)
  result = 0
  (2...num).each do |i|
    result = i if (num % i) == 0 && i.prime?
  end
  puts result
end

largestPrime(13195)

I will update this code as soon as I find a better solution but for now it works.

Design Patterns

I’ve got this book last week. It’s the most expensive I’ve ever bought and I do not regret!
I am still in the beginning and learned what are Design Patterns, the catalog of the 23 design patterns in this book and how they solve problems. After, will be shown how to select and use a design pattern, a case study and then we delve into each one of the patterns. The authors explain Object Oriented Design and how objects interact with each other as an introduction.

IMG_20160726_143709727

The good thing about this is that the book has a guide and is suited for rookie readers which is awesome!