Ruby number formatting: only show decimals if there are any
Warning: Because of (unclear) rounding issues and missing decimal places (see examples below),
do NOT use this when dealing with money. Use our amount helper instead.
In Ruby, you can easily format strings using % (short for Kernel#sprintf):
'%.2f' % 1.23456 #=> 1.23
'%.2f' % 2 #=> 2.00
However, what if you only want the decimals to be shown if they matter? There is g! It will limit the total number of displayed digits, disregarding...
CSS: Opacity is not inherited in Internet Explorer
Non-static elements will not inherit their parent's opacity in IE for no good reason. This can lead to unexpected behaviour when you want to fade/hide an element and all its children.
To fix it, give the parent element defining the opacity a non-static positioning. For example:
.parent {
opacity: 0.2;
position: relative; /* for IE */
}
While the linked article describes this problem for IE9 and below, I have encountered the same issue in IE10 and IE11.
Just go away, Internet Explorer!
MySQL 5.6 slightly changes DECIMAL data type
About
A MySQL DECIMAL column is used when it is important to preserve exact precision. It takes two parameters, where precision is the total number of digits and scale the number of digits to the right of the decimal point. A DECIMAL(6,2) column may store numbers up to 9,999.99.
In Rails, a decimal column definition looks like this: t.decimal :amount, :precision => 6, :scale => 2.
Issue
MySQL prior to 5.6 stored leading zeros (0003.1) and +/- characters (+2.1) within the column. However, **it would permit storing ...
The new Modularity 2 syntax
We have released Modularity 2. It has many incompatible changes. See below for a script to migrate your applications automatically.
There is no does method anymore
We now use traits with the vanilla include method:
class Article < ActiveRecord::Base
include DoesTrashable
end
When your trait has parameters, use square brackets:
class Article < ActiveRecord::Base
include DoesStripFields[:name, :brand]
end
Note how you ...
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....
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...
Ruby constant lookup: The good, the bad and the ugly
In Ruby, classes and modules are called constants. This card explains how Ruby resolves the meaning of a constant.
The good
E. g. in the following example, Array could mean either Foo::Array or simply Array:
class Foo
def list
Array.new
end
end
What Ruby does here is to see if the name Array makes sense inside of Foo::, and if that fails, resolves it to ::Array (without a namespace).
The bad
This is relevant for old Ruby versions. Ruby 2.5+ removes top-level constant lookup whi...
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
Spreewald 0.8.0 brings a file attachment step
# Attach a file
#
# Example:
#
# Company.new.logo = File.new…
#
# Given the file "…" was attached as logo to the company above
#
#
# Example:
#
# class Gallery
# has_many :images, :as => :owner
# end
#
# class Image
# belongs_to :owner, polymorphic: true
# end
#
# # so container = Image.new; container.file = File.new… , container.owner = object
#
# Given the file "…" was attached as Image/file to the company above
#
#
# Example:
#
# Set updated_at with
#
# Given … above at "2011-11-11 11:11"
#
howto fix spreewald issue „database configuration does not specify adapter (ActiveRecord::AdapterNotSpecified)“
This error occurs when you already have a database.yml which defines the database for the cucumber environment instead of test. (Spreewald database.sample.yml has changed)
Fix
Change cucumber to test in your databse.yml
test: # <---
adapter: mysql2
database: spreewald_test
encoding: utf8
host: localhost
username: root
password: password
Whitelist Carrierwave attributes correctly
Say you have a User with a Carrierwave attribute #avatar:
class User < ActiveRecord::Base
mount_uploader :avatar, AvatarUploader
end
When whitelisting the avatar field in the controller, you might do this:
params[:user].permit(:avatar)
But you probably want this:
params[:user].permit(:avatar, :avatar_cache, :remove_avatar)
In this example:
-
:avatar_cacheallows a newly upload image to persist through form roundtrips in the case of validation errors (something that isn't possibl...
How to find out the type of a model's attribute
When you want to find out the data type of an attribute, you can just use ActiveRecord's columns_hash method.
It returns a hash of column objects that include a type attribute (and more database-related information).
Example:
Contract.columns_hash['id'].type
=> :integer
Contract.columns_hash['active'].type
=> :boolean
Contract.columns_hash['updated_at'].type
=> :datetime
FooLimitExceeded Quota problem with OpenStack
If you get a Quota error with OpenStack, it doesn't have to be what it tell.
For example, I've got this message because the RAM Quota was exceed:
2013-11-11 17:13:25 WARNING nova.compute.api [req-bdasdfas-f5d7-4fcd-bf1b-asdfasdf229e ba2c21dadasdfasdf1d6asdfasdfa0f bfe2db2aasdfasdfb8ea686asdfasdfb] Quota exceeded for bfe2db2aasdfasdfb8ea686asdfasdfb, tried to run 1 instances. Cannot run any more instances of this type.
2013-11-11 17:13:25 INFO nova.api.openstack.wsgi [req-bd003113-f5d7-4fcd-bf1b-asdfasdf229e ba2c21dadasdfasdf1d6asdf...
Monitoring a network connection from a remote host
Sometimes you need to monitor a connection from your machine to a specific, single host or network in order to identify which network hop between your machine and the target causes trouble. You can use the following shell script to easily achieve this kind of monitoring.
If the target host is unable to respond to the specified number of ICMP packets, you will get an eMail together with a mtr to see on which hop the problem occurs.
#!/bin/bash
TARGET=8.8.8.8 # Target host or IP address to be monitored.
MAIL_RECIPIENT=you@exam...
Let the browser choose the protocol
Use protocol independent URLs whenever possible so that the browser will choose the protocol related to the protocol which the page is delivered with.
Example issues
- When your page is delivered via
httpsand you provide a youtube video only viahttpthe most browsers (e.g. Firefox, Chrome) won't display the video. - When you deliver your youtube video via
https://youtu.be/jyElDp98HdIyour test which checks that the embeded video is rendered in the view will fail because your test server doesn't use https
Solution
Let your lin...
Font Combiner
Font Combiner offers a way to tweak and adjust any TTF or OTF font (license permitting), by bringing in font glyphs as vector shapes, providing a completely overhauled font generated to the user's specification with alternative metrics options, alternative hinting types, kerning and spacing options and the facility to make any average free font look great.
Stubbing out external services with an embedded Sinatra application
One of many useful techniques when your test suite needs to talk to a remote API.
Enable NewRelic monitoring [for Rails] on specific hosts only
If you need to enable NewRelic monitoring on certain machines within the same Rails environment, a simple solution is to utilize the respective hostnames of you machines.
For example, if you have 8 application servers (e.g. app1.example.com, app2.example.com, ...) and want to enable NewRelic on app1 and app2 only, utilize those steps to do so:
- Put the attached file into your config directory (
config/custom_new_relic_configuration.rb). - Specify on which hosts NewRelic should be enabled (see
NEWRELIC_HOSTSconstant and list ...
A simpler default controller implementation
Rails has always included a scaffold script that generates a default controller implementation for you. Unfortunately that generated controller is unnecessarily verbose.
When we take over Rails projects from other teams, we often find that controllers are the unloved child, where annoying glue code has been paved over and over again, negotiating between request and model using implicit and convoluted protocols.
We prefer a different approach. We believe that among all the classes in a Rails project, controllers are some of the hardest to...
Fix "An error occurred while installing debugger-linecache" with Ruby 1.9.3
You're better off using debugger-ruby_core_source:
gem install debugger-ruby_core_source
If you can't do this, try the following.
Here is how to fix the following error when installing the debugger gem fails:
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension
Note: The following example is for a project using Ruby 1.9.3-p448 -- adjust accordingly for your project.
-
Fetch the source for your Ruby version, if you do not yet have it:
rvm fetch ruby-1.9.3-p448 -
Install t...
How to not repeat yourself in Cucumber scenarios
It is good programming practice to Don't Repeat Yourself (or DRY). In Ruby on Rails we keep our code DRY by sharing behavior by using inheritance, modules, traits or partials.
When you reuse behavior you want to reuse tests as well. You are probably already reusing examples in unit tests. Unfortunately it is much harder to reuse code when writing integration tests with Cucumber, where you need to...
Geordi: Choose your firefox version for cuc
Geordi 0.16+ supports running selenium tests with project-specific firefox versions.
Just update the gem. It will still default to using the old 5.0.1 firefox. If you want another one, add a file .firefox-version to your project, containing your preferred version.
geordi cucumber will prompt (and guide) you to install the given version. You can delete any old installation sitting in /opt/firefox-for-selenium if you have one.
VCR: Alternative way of mocking remote APIs
If you need to test interaction with a remote API, check out the VCR gem as an alternative to Webmock or stubbing hell.
The idea behind VCR is that is performs real HTTP requests and logs the interaction in a .yml file. When you run the test again, requests and responses are stubbed from the log and the test can run offline.
It's a great way to mock network requests to an external service without going through the pain of log...