Cucumber – Carrierwave – ImageUploader – Variable class

Problem
You would like to test the carrierwave imageuploader with a cucumber test, but you would also like to use a generic step that can be used with different classes and different image file column names.

Solution
Use the following and perhaps put it a file named features/common_steps.rb

Then /^the url for the column "([^"]*)" of model "([^"]*)" should be "([^"]*)"$/ do |col,mdl,url|
  # First get tne class name from the mdl argument by using the Kernel.const_get method
  m = Kernel.const_get(mdl).first
  # And then use the send with the column name (col) to call the model's field,
  # the url method of ImageUploader to get the full path
  # and basename to get only the file name
  File.basename(m.send(col).url).should == url
end

ActiveSupport::TimeWithZone comparisons

Problem
You have two dates that you want to compare in your Rails application, which are both ActiveSupport::TimeWithZone.

Although they both look identical, when you are trying to compare them for equality (using ==), you get back false as a result.

 

Solution

These dates can have a difference in milliseconds that doesn’t normally get displayed. So first of all try to use to_f to see if they really have a difference.

If they do, then you would need to compare them by converting them to integers first as in :

date_a.to_i == date_b.to_i

and you should be getting back true

Secure Random passwords in Ruby

Problem
You would like to use a random password in ruby. Most solutions describe using the Digest library (Digest::SHA1).

Solution
According to the post here, you can achieve the same by using ActiveSupport’s secure_random library.
To use it in Ruby outside Rails use:

require 'active_support/secure_random'
ActiveSupport::SecureRandom.hex(10)
ActiveSupport::SecureRandom.base64(10)


and inside rails:

SecureRandom.hex(10)