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;
}

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!

Solving Algorithms – Bubble Sort

Why are solving algorithms Adnilson, shouldn’t you work on building applications? Yes, you are right! The thing with algorithms is that it helps you solve problems and are good to make your mind look for solutions. This way you build a blueprint and whenever you get a problem you tackle the problem instead of being tackled by it.

In Ruby things sometimes are too easy and today I will go back to school and review the bubble sort, this algorithm is not the most efficient way of sorting but is a simple and cool exercise.
In Ruby if you want to sort say, an array you can do it by doing array.sort and bam! There it is.
The code:

 

length = array.length - 1
loop do
  swapped = false
  (0...length).each do |i|
    if array[i] > array[i+1]
      array[i], array[i+1] = array[i+1], array[i]
      swapped = true
    end
  end
  break if !swapped
end

puts array

I guess the code speaks for itself. In a lower level language the program would have an extra variable to store the value of one of the array contents in order to swap.
The first time I did this was in Pascal, then Fortran in college.