Cucumber / Selenium: Access and test document title
If you want to test that a certain text is contained within the document title of your page, you can do so using Selenium and a step such as
Then /^"(.*?)" should be shown in the document title$/ do |expectation|
  title = page.driver.browser.title
  title.should include(expectation)
end
Careful with '||=' - it's not 'memoize'
When you do something like this in your code:
def var_value
  @var ||= some_expensive_calculation
end
Be aware that it will run some_expensive_calculation every time you call var_value if some_expensive_calculation returns nil.
This illustrates the problem:
def some_expensive_calculation
  puts "i am off shopping bits!"
  @some_expensive_calculations_result
end
When you set @some_expensive_calculations_result to nil, ||= runs some_expensive_calculation every time....
Choosing the Right Size and Format for Icons
Icons Sizes for Windows, MacOS X, iOS, Android and Linux. It's a mess!
Prevent long strings from stretching your <table> with CSS
- Give the table a style table-layout: fixed
- Give the cells in the first row a width
- The same width will be automatically used for following rows
Opal, A new hope (for Ruby programmers)
Opal is a source to source ruby to javascript compiler, corelib and a runtime implementation that currently passes 3000 rubyspecs w/a reachable goal of passing them all.
Rails always tries to use a layout with the same name as your controller
If you have a FooController and also have a layout app/views/layouts/foo.html, Rails will use this without being told so.
This is super convenient except never.
Threads and processes in a Capybara/Selenium session
TLDR: This card explains which threads and processes interact with each other when you run a Selenium test with Capybara. This will help you understand "impossible" behavior of your tests.
When you run a Rack::Test (non-Javascript) test with Capybara, there is a single process in play. It runs both your test script and the server responding to the user interactions scripted by your test.
A Selenium (Javascript) test has a lot more moving parts:
- One process runs your test script. This is the process you...
Careful when writing to has_many :through associations
tl;dr: Using has_many associations with a :through option can lead to lost or duplicate records. You should avoid them, or only use them to read records.
Consider this:
class User < ActiveRecord::Base
end
class Party < ActiveRecord::Base
  has_many :invitations
  has_many :users, through: :invitations, include: :user, order: 'users.name'
end
class Invitation < ActiveRecord::Base
  belongs_to :party
  belongs_to :user
  
  after_create :send_invite
  
  def send_invite
  ...
Howto set jQuery colorbox overlay opacity
Setting the colorbox opacity by hash parameter when initializing doesn't work the way like the documentation tells you.
  $(selector).colorbox({ ..., opacity: 0.5, ... }); // has no effect
The opacity value of 0.5 will be overwritten by the inline style attribute style="opacity: 0.9" that colorbox sets.
To manually set the opacity you have to add the following css rule
  #cboxOverlay { opacity: 0.5 !important; }
Sort a Ruby array with multiple criteria
If you want to sort a Ruby array with a primary, secondary, etc. criterium, use a sort_by that contains a block:
users.sort_by { |user| [user.age, user.name] }
This trick also works with our natural sort method.
How to fix "undefined method `name' for Array" error when running bundled commands on Ruby 1.8.7 + Rails 2.3
On recent/fresh installations of Ruby 1.8.7 you may encounter this error why calling any bundled binary (or just bundle exec):
/home/arne/.rvm/gems/ruby-1.8.7-p374@global/gems/rubygems-bundler-1.4.2/lib/rubygems-bundler/noexec.rb:75:in `setup': undefined method `name' for #<Array:0x7fe04783ef30> (NoMethodError)
  from /home/arne/.rvm/rubies/ruby-1.8.7-p374/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:29:in `map'
  ...
Apparently, this is due to bundler (or maybe the rubygems-bundler that RVM supplies by default) no lon...
Skype screen sharing: Select which monitor to share
If you have multiple monitors and want to share a given screen with your call partner, drag the caller window to the desired monitor, then start sharing.
This is for Skype 4.2+ on Linux.
Auto-coerced virtual attributes with Virtus
We've since created ActiveType which has a restricted subset of Virtus' features. It might be enough for your needs.
We sometimes give our ActiveRecord models virtual attributes for values that don't need to be stored permanently.
When such a virtual attribute should contain integer values you might get unexpected behavior with forms, because every param is a string and you don't get the magic type casting that Rails would give you if it ...
Virtus can coerce structured values
Just a quick note that Virtus can coerce (auto-cast) structured values like collections or maps:
class Klass
  include Virtus.model
  attribute :dimensions, Hash[Symbol => Float]
  attribute :numbers, Array[Integer]
end
Check out the Virtus README, it's full of nice things like this!
Careful when calling a Ruby block with an array
When a Ruby block or proc takes multiple parameters, and you call it with an Array, Ruby will unexpectedly splat the array elements:
block = proc { |a, b| "a=#{a}, b=#{b}" }
block.call(1, 2)   # "a=1, b=2"
block.call([1, 2]) # "a=1, b=2"
Note that lambdas behave as expected:
block = lambda { |a, b| "a=#{a}, b=#{b}" }
block.call(1, 2)   # "a=1, b=2"
block.call([1, 2]) # ArgumentError: wrong number of arguments (1 for 2)
Embed Font Awesome icons from your CSS
An annoying part of using font icons is that the icons usually need to live in the DOM. This is a step back from the time when we defined raster icons with background-image, in the CSS.
It doesn't have to be that way.
Copy the attached file font-awesome-sass.css.sass to your assets (we recommend /vendor/asset-libs/font-awesome-sass).
You can now use Font Awesome icons from your Sass files:
@import font-awesome-sass
...
CarrierWave: Don't use #url when you mean a file path
CarrierWave attachments have two distinct methods #url and #path which appear to behave the same:
document.file.url   # => /storage/documents/4/letter.doc
document.file.path  # => /storage/documents/4/letter.doc
However, starting with CarrierWave 0.9, #url will properly escape high-ASCII characters:
document.file.url   # => /storage/documents/4/h%C3%BCte.doc
document.file.path  # => /storage/documents/4/hüte.doc
So always use #url if you mean an actual URL (e.g. to display an <img>). But use #path if y...
Build cronjobs or list next dates
"CronMaker is a utility which helps you to build cron expressions." Check it out at http://www.cronmaker.com/.
To simply check syntax of a cron schedule, paste it into your personal crontab file using crontab -e. If you have syntax errors, the crontab command will complain like this:
crontab: installing new crontab
"/tmp/crontab.3szkFA/crontab":0: bad minute
errors in crontab file, can't install.
Do you want to retry the same edit? (y/n) y
Ruby: How to measure code execution time in an IRB or Rails console
Modern IRB has time measurement built in.
measure # Enable
measure :off # Disable
Custom
Should your version of IRB not offer this feature, you can measure manually. Paste this method into your console:
def time(&block) puts Benchmark.measure(&block) end
Now time { Some.lengthy_task } will behave similar to the bash time command. Of course you can do much more with the Benchmark object than just putsing it – adapt to your needs.
Use the Ruby debugger on Rails 2 script/runner scripts
This card needs to be updated for Rails 3+.
Since there is no --debugger flag you need to run:
rdebug script/runner lib/scripts/something.rb
That will open an debugging IRB right away, like this:
require File.dirname(__FILE__) + '/../config/boot'
(rdb:1) _
Enter c to continue and reach your actual debugger call. Then, debug away.
If nothing happens for you: Make sure ruby-debug is available in the Gemfile and you require it.
Bash: How to only do things in interactive shells
When you print something from within your .bashrc file you will run into trouble when copying something onto your machine using scp for example.
This is because the output from your .bashrc interferes with scp. The solution is to decide whether the bash shell is started interactively (you start a terminal on your screen) or not (scp).
if [ ! -z "$PS1" ]; then
  # This happens in interactive shells only and does not interfere with scp.
  echo "Learn!"
fi
Howto provide a single page preview for PDF & TXT with carrierwave
Assert rmagick provision ...
Gemfile
gem 'rmagick', '2.13.2' # at this moment the latest stable version
config/initializer/carrierwave.rb
require 'carrierwave/processing/rmagick'
... and define a custom processor
MyUploader.rb
class MyUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick
  def cover
    manipulate! do |frame, index|
      frame if index.zero? # take only the first page of the file
    end
  end
  version :preview do
    process :cover
    process :resize_to_fit => [310,...
How to silence "I18n.enforce_available_locales" deprecation warnings
Before Rails 3.2.14, when supplying an invalid locale to I18n, it would fall back to its config.i18n.default_locale (which is :en by default). Eventually, this will be changed to raise an error by default -- for now, it shows a deprecation warning.
Since Rails 3.2.14 and 3.2.15 did not include security updates, you might not have applied them and probably now encounter these deprecation warnings after upgrading to 3.2.16 (or 4.0.2):
[deprecated] I...