Consul: Querying a power that might be nil
Consul 0.6.1+ gives your Power
class a number of static methods that behave neutrally in case Power.current
is nil
. This allows you to create authorization-aware models that still work when there is no user at the end of a web browser, e.g. on the console, during tests or during batch processes.
You will often want to access Power.current
from another model, to e.g. iterate through the list of accessible users:
class UserReport
def data
Power.current.users.c...
Understanding race conditions with duplicate unique keys in Rails
validates_uniqueness_of
is not sufficient to ensure the uniqueness of a value. The reason for this is that in production, multiple worker processes can cause race conditions:
- Two concurrent requests try to create a user with the same name (and we want user names to be unique)
- The requests are accepted on the server by two worker processes who will now process them in parallel
- Both requests scan the
users
table and see that the name is available - Both requests pass validation and create a user with the seemingly available name...
Geocoding Strategies - Google Maps API
The attached article outlines considerations when choosing client-side vs. server-side implementations of the Google Geocoding APIs (geocoder, directions, not maps drawing). The main points are:
- On the server side you only get a fixed daily request quota
- On the client side the quota is per-client, so basically unlimited
- When implementing APIs on the server-side, be aware that quota is measured by IP. When hosting in the cloud **you don't always know which other services might...
Phusion Passenger 4 Technology Preview: Out-Of-Band Work – Phusion Corporate BlogPhusion Corporate Blog
The Out-of-Band Work feature allows one to perform arbitrary long-running work outside the request/response cycle without blocking HTTP clients. The primary use case is to run the garbage collector in between cycles so that your requests will finish faster because they will not be interrupted by the garbage collector.
Using Apache Benchmark (ab) on sites with authentication
Apache HTTP server benchmarking tool (ab
) is a nice tool to test performance on sites delivered by HTTP. If the site you're about to test is placed behind a login, follow these steps to successfully use ab
on it.
- Open the site to test in the browser of your choice. Do not login yet.
- Use developer tools to show all cookies used by the site. (Chrome: Ctrl+Shift+i, open the 'Resources' tab and click on the site below 'Cookies' on the left. Firefox: Right-click on the site, open 'We...
Ruby: How to ensure a Tempfile's extension
If you use Tempfile
and pass your own filename containing an extension, it will just be consumed by the Tempfile's filename:
>> Tempfile.new('foobar.xlsx').path
=> "/tmp/foobar.xlsx20130115-19153-4ykpwm-0"
If you want to keep the file extension, pass filename and extension as an array:
>> Tempfile.new([ 'foobar', '.xlsx' ]).path
=> "/tmp/foobar20130115-19153-1xhbncb-0.xlsx"
How to get the hostname of the current machine in Rails or a Ruby script
Use Socket.gethostname
. So for a machine whose hostname is "happycat", it will look like this:
>> Socket.gethostname
=> "happycat"
That should work right away for your Rails application. For plain Ruby, you first need to do:
require 'socket'
If you don't want to use Socket
for some reason, you can still just use the hostname
command, at least on non-Windows machines. Keep in mind that you need to remove trailing white space from the result of the system call.
>> `hostname`
=> "happycat\n"
>> `hostname`.stri...
Why your browser loses cookies when following hyperlinks from an Excel spreadsheet or Word document
Microsoft Office pre-fetches hyperlinks using an internal DLL (which doesn't know about your cookies), follows all redirects and opens your browser with the result. This is because of stupidity.
The "fix" is to not redirect but just render a text like "access denied" with 200 OK when you see that request.env['HTTP_USER_AGENT'].include?('ms-office')
.
Force GitHub Pull Requests to update the diff against its target branch
When you have a Pull Request on GitHub that includes commits from another Pull Request, you will still see them after the "child" PR has been merged. Unfortunately, GitHub won't automatically update the diff (or commit list).
Here is what worked for me:
- Check out the target branch
git checkout my-target-branch
- Make sure you are up to date against origin (e.g.
git fetch
andgit status
). You should be 0 commits ahead or behind.
- Add and commit a file
touch .please-update
git add .please-update
- `gi...
How to provoke Selenium focus issues in parallel test processes
As attachments to this card you will find a Cucumber feature and supplementing step definition that you can use to provoke Selenium focus issues that only occur when two focus-sensitive Selenium scenarios run at the same time (probably with parallel_tests). This can help you to detect and fix flickering integration tests.
The attached feature works by going to your root_path
and focusing a random form element every 5...
Analyse TCP/UDP traffic with netcat
Sometimes you want to see what data you get through a TCP or UDP connection.
For example, you want to know how a HTTP Request look like.
It's very easy with netcat.
Example to listen on port 80 and the output gets to stdout.
sudo nc -kl 80
It's also possible write it into a file:
sudo nc -kl 80 > output.txt
If you use Ports higher than 1000 you don't need to be root (sudo).
Custom bash autocompletion
The bash offers control over the behavior of autocompletion.
The most primitive example is this (just run it in your bash; if you want it available everywhere, put the complete ...
line into your .bashrc
):
> complete -W "list of all words for an automatic completion" command_to_be_completed
> command_to_be_completed a<TAB>
all an automatic
With complete
you define how the specified command shall be completed. For basic needs, -W
(as in "word list") should be enough, but you may also specify a function, a glob patte...
Performance analysis of MySQL's FULLTEXT indexes and LIKE queries for full text search
When searching for text in a MySQL table, you have two choices:
- The LIKE operator
- FULLTEXT indexes (which currently only work on MyISAM tables, but will one day work on InnoDB tables. The workaround right now is to extract your search text to a separate MyISAM table, so your main table can remain InnoDB.)
I always wondered how those two methods would scale as the number of records incr...
Custom error pages in Rails
Static error pages
To add a few basic styles to the default error pages in Rails, just edit the default templates in public
, e.g. public/404.html
.
A limitation to these default templates is that they're just static files. You cannot use Haml, Rails helpers or your application layout here. If you need Rails to render your error pages, you need the approach below.
Dynamic error pages
- Register your own app as the applicatio...
Render Sass stylesheets dynamically
If - for whatever reason - you have to render stylesheets dynamically, the following snippet might be of help. It emulates what "sprockets" would to when precompiling your assets, and give your stylesheets access to all the regular bells and whistles (like asset_path
, proper @import
s etc):
class DynamicStylesheetsController < ApplicationController
def show
logical_path = RELATIVE_PATH_TO_YOUR_TEMPLATE
path = File.join(Rails.root, logical_path)
template = Sass::Rails::SassTemplate.new(path)
environment = ...
Git: Improve your commits by reviewing changes one-by-one
Git commits should be very deliberate, and only contain changes that you really want to be in there. In order to reduce the chance to accidentally commit something you didn't intend, review your changes before committing.
My preferred way of doing this is (only using git)
git add -N . # Add all paths, but not their contents
git add -p
Git will now show you all your changes in small chunks and ask you in an interactive mode whether you really want to add them.
The most helpful commands are
- y: yes (add the change)
- ...
Firefox makes an OPTIONS request you don't expect
If some AJAX functionality does not work, but you see Firefox making an OPTIONS
request, the reasons is most likely this:
You're accidently trying to talk to a different domain (or switching from http
to https
), and Firefox tries to find out if that is okay, according to the "Cross-Origin Resource Sharing" standard.
Force absolute URLs for parts of a view or controller
You know that you can force absolute URLs throughout a response. Now you want to modify URLs similarly, but only in parts of a view (or controller) logic. Here is how.
Note: this has only been tested on a Rails 2 application. It should work similarly for Rails 3.
Put this into your ApplicationController
:
def rewrite_options(*args)
options = super
options.merge!(:only_path => false) if @with_full_urls
options
end...
How to change the hostname in Cucumber features
Capybara uses www.example.com
as the default hostname when making requests.
If your application does something specific on certain hostnames and you want to test this in a feature, you need to tell Capybara to assume a different host.
Given /^our host is "([^\"]+)"$/ do |host|
page.config.stub app_host: "http://#{host}"
# In older Capybaras (< 2.15) you needed to do this instead:
Capybara.stub app_host: "http://#{host}"
end
You can now say:
When I go to the start page
Then I should not see "Home ...
Capybara 2.0 has been released
The gem author Jonas Nicklas highlights in a Google Groups post that the release
- is not backwards compatible to 1.x versions of Capybara
- does not support Ruby 1.8.x anymore
- removes confusion with Rails' built in integration tests (you put capybara rspec integration tests into the
spec/feature/...
folder) and the:type
metadata has been changed from:request
to:feature
- throws exceptions when trying to interact with an element whose identifier is...
How to move a window to the next monitor on Xfce, Mate and other X Window Managers
Since I use this a lot in my daily work and there were no scripts working properly for me, I made one myself.
It's actually not bound to Xfce but should work on any window manager (haven't tried it, though).
Installation
-
If you don't yet have
xdotool
, install it:sudo apt-get install xdotool
-
If you don't yet have
wmctrl
, install it:sudo apt-get install wmctrl
-
Store the attached file in some place that's in your
PATH
.
The cool kids use~/bin/
. -
Make it executable: `chmod +x ~/bin/move-to-next-mo...
Internet Explorer will download CSS files twice, if referenced via scheme-less URLs
You can use scheme-less URLs (or protocol-relative URLs) to have browsers use the current protocol (HTTP or HTTPS) when loading content referenced with such an URL.
A protocol relative URL doesn’t contain a protocol. For example,
http://stevesouders.com/images/book-84x110.jpg
becomes//stevesouders.com/images/book-84x110.jpg
Browsers substitute the protocol of the page itself for the resource’s missing protocol. Problem solved!
But:
Internet Explorer 7 & 8 will download st...
Firefox: Inspecting mixed content warnings (and how to enable them)
Having your site run on SSL is worthless when you include content over an unsafe connection (HTTP).
Here is how to hunt down mixed content with Firefox.
How to enable mixed content alerts
If your Firefox does not warn you about mixed content on pages (mine did not), you can enable it again:
Visit about:config and search for security.warn_viewing_mixed
. If it's set to false
, set it back to true
again.
Seeing which URLs are fetched from unsecured connections
Firefox 16+ will show you mixed content in its "Web Console".
Open it ...
Cucumber: Wait for any requests to finish before moving on to the next scenario
Background
Generally, Selenium tests use the browser to interact with the page. If it's unavailable, a timeout error is thrown.
Now, consider a scenario like this:
@javascript
Scenario: Receive an e-mail after clicking the fancy link
When I follow "fancy link"
Then I should have an e-mail with the subject "Hello"
When the last step in the scenario passes, you are done. Right? Wrong.
Why it's not enough
What if clicking our "fancy link" above sends the e-mail that we expect, but it also does stuff on the server...