Getting permanent links to files on Github or Gitlab
Please don't simply copy line number links from Github. The URL usually contains a branch name like master
which will change over time:
https://github.com/makandra/upjs/blob/master/lib/assets/javascripts/up/link.js.coffee#L76
If someone now posts an insertion or deletion to that file into master
your link points to the wrong line!
A better way is to press the Y
key after clicking on a line number. This will transform the URL to another URL that points to the particular commit:
https://github.com/makandra/upjs/blob/b3b14...
Detecting when fonts are loaded via JavaScript
Webfonts are not always available when your JavaScript runs on first page load. Since fonts may affect element sizes, you may want to know when fonts have been loaded to trigger some kind of recalculation.
Vanilla JavaScript / Modern DOM API
In modern browsers (all but IE and legacy Edge) you can use document.fonts
. Use load
to request a font and receive a Promise that will be resolved once the font is available. Example:
document.fonts.load('1rem "Open S...
Ruby: Enumerable#partition
If you want to sort values from an enumerable into two arrays based on whether they match a certain criteria or not, Enumerable#partition
can come in handy.
# Enumerable#partition returns two arrays,
# the first containing the elements of enum
# for which the block evaluates to true,
# the second containing the rest.
(1..6).partition { |v| n.even? } #=> [[2, 4, 6], [1, 3, 5]]
Works well with destructuring assignment, too.
even, odd = (1..6).partition { |n| n.ev...
Sharing cookies across subdomains with Rails 3
To achieve this goal you have to setup the session store like the following example:
MyApp::Application.config.session_store(
:cookie_store,
{
:key => '_myapp_session',
:domain => :all, # :all defaults to da tld length of 1, '.web' has length of 1
:tld_length => 2 # Top Level Domain (tld) length -> '*.myapp.web' has a length of 2
}
)
The invconvenient side effect for local development
… or: Why do I get "Can't verify CSRF token authenticity" even if csrf token is present?
As `:domain => :all...
How to create giant memory leaks in AngularJS (and other client-side JavaScript)
This guide shows how to create an AngularJS application that consumes more and more memory until, eventually, the browser process crashes on your users.
Although this guide has been written for Angular 1 originally, most of the advice is relevant for all client-side JavaScript code.
How to observe memory consumption
To inspect the amount of memory consumed by your Javascripts in Chrome:
- Open an incognito window
- Open the page you want to inspect
- Press
Shift + ESC
to see a list of Chrome processes...
Remove URLs from the Google index
Obviously, you only can do this for your own sites.
You need to authenticate a domain you want to remove content from via Webmaster Tools.
To remove a URL:
- Open Webmaster Tools
- Select the respective site from the list of domains under your control
- Choose "Google Index" from the menu left
- Click "Remove URL"
Rails: Running specific migrations
When running migrations with rake db:migrate
, there's the STEP
and VERSION
parameters that you can pass to nearly all commands.
# Migrate
rake db:migrate
rake db:migrate STEP=2
rake db:migrate VERSION=20080906120000
# Redo
rake db:migrate:redo
rake db:migrate:redo STEP=2
rake db:migrate:redo VERSION=20080906120000
# Rollback (starting from latest migration)
rake db:rollback
rake db:rollback STEP=2
# Run the `down` migration path of a certain migration file
rake db:migrate:down VERSION=20080906120000
Angular + ui-router: Make links work in a new tab
If your angular app is not served on /
, but on a different url (say /admin
), links generated with ui-router will not work when you open them in a new tab.
Fix this by adding this tag in your <head>
:
<base href='/admin#/'>
Helper method:
def base_tag
tag(:base, href: request.path_info + "#/")
end
Rails index route for resources named after uncountable substantives
Using uncountable resources is not recommended as it breaks Rails' magic, e.g. when using form_for
. You'll always be better off using simple pluralizable resources.
Rails automatically creates path names for routes defined via the resource
method. When you put resource 'user'
into config/routes.rb
, you can call users_path
and get the path to the index
action in the UsersController
: /users
.
However, if you have an uncountable resource like Sheep
, you cannot access the index action via sheep_path
, because it will...
How to circumvent Firefox's "Document expired" page in Selenium tests
When navigating back to a page that was received from a POST request, undesired side effects may happen. Therefore, modern browsers try to keep users from doing so, i.e. Firefox 24 displays an error page explaining what's wrong. If the user presses "Try Again", it shows an additional alert asking whether the user is certain.
Solution
If you need to circumvent this protection, e.g. to test that your application behaves correctly despite being misused, do this:
page.execute_script 'history.back()'
page.execute_script 'retryThis(this)...
Jasmine: Testing AJAX calls that manipulate the DOM
Here is a Javascript function reloadUsers()
that fetches a HTML snippet from the server using AJAX and replaces the current .users
container in the DOM:
window.reloadUsers = ->
$.get('/users').then (html) ->
$('.users').html(html)
Testing this simple function poses a number of challenges:
- It only works if there is a
<div class="users">...</div>
container in the current DOM. Obviously the Jasmine spec runner has no such container. - The code requests
/users
and we want to prevent network interaction in our uni...
How to upgrade Cucumber on Rails 3+
-
Run
bundle update cucumber capybara cucumber-rails
to update to the newest versions. -
Backup your
features/support/path.rb
to be able to add your own paths again after the cucumber installation script in step 4. -
Backup your
features/support/env.rb
file to be able to reintegrate parts like your blueprints setup:ENV["RAILS_ENV"] ||= "cucumber" require File.expand_path(File.dirname(__FILE__) + '/../../config/environment') require 'spec/support/blueprints'
-
Run `$ rails generate cucumber:install --capyba...
Taking screenshots in Capybara
Capybara-screenshot can automatically save screenshots and the HTML for failed Capybara tests in Cucumber, RSpec or Minitest.
Requires Capybara-Webkit, Selenium or poltergeist for making screenshots. Screenshots are saved into $APPLICATION_ROOT/tmp/capybara
.
Manually saving a page
Additionally you can trigger the same behavior manually from the test using Capybara::Session#save_and_open_page and [...
Action Mailer Previews
Rails includes a way to see what an e-mail will look like.
Integration to RSpec
All you need to do is implement a preview-class in spec/mailers/previews/notifier_preview.rb
:
class NotifierPreview < ActionMailer::Preview
def welcome
Notifier.welcome(User.first)
end
end
And adapt the preview load path in your application.rb
:
config.action_mailer.preview_path = "#{Rails.root}/spec/mailers/previews" # For Rails < 7.1
config.action_mailer.preview_paths << "#{Rails.root}/spec/mailers/previews" # For Rails >=...
Managing vendor libraries with the Rails asset pipeline
The benefit of the Rails asset pipeline is that it compiles your stylesheets and javascripts to a single file, respectively. However, the consequences are startling if you don't understand them. Among others, the raw asset pipeline requires you to have all your asset libraries in the same folder, which quickly becomes confusing as your set of assets grows. To overcome this, we have two different solutions.
Custom solution
We are using a custom workaround to keep library files apart in their own directories. To avoid b...
Asset Pipeline Basics
The Rails asset pipeline improves delivery of application assets (javascripts, stylesheets, images, fonts). Here are some basic facts about its inner workings.
No magic
Manifests are the handle on your assets:
app/assets/stylesheets/application.css # use via: stylesheet_link_tag 'application'
The asset pipeline only considers files you explicitly require within your manifest files. The most common directives used in manifests are require some/file
and require_tree some/directory
. Paths may be **relative to the current director...
Install or update Chromedriver on Linux
Option 0: Download from the official page (preferred)
- Open https://googlechromelabs.github.io/chrome-for-testing/
- In Section "Stable" > chromedriver / linux64 > Download ZIP from URL
- Take the
chromedriver
binary from the ZIP file and put it e.g. into~/bin
.
Chromedriver must be available in your path. You can add ~/bin
to your path like this:
echo "export PATH=$PATH:$HOME/bin" >> $HOME/.bash_profile
If you're also using Geordi, disable automatic updating of chromedriver in ~/.config/geordi/global.yml
:
a...
The Easiest Way to Parse URLs with JavaScript
A very clever hack to parse a structured URL object is to create a <a>
element and set its href
to the URL you want to parse.
You can then query the <a>
element for its components like schema, hostname, port, pathname, query, hash:
var parser = document.createElement('a');
parser.href = 'http://heise.de/bar';
parser.hostname; // => 'heise.de'
pathname = parser.pathname; // => '/bar'
if (pathname[0] != '/')
pathname = '/' + pathname // Fix IE11
One advantag...
jpmcgrath/shortener
Shortener is a Rails Engine Gem that makes it easy to create and interpret shortened URLs on your own domain from within your Rails application. Once installed Shortener will generate, store URLS and “unshorten” shortened URLs for your applications visitors, all whilst collecting basic usage metrics.
How to combine "change", "up", and "down" in a Rails migration
Rails migrations allow you to use a change
method whose calls are automatically inverted for the down path. However, if you need to some path-specific logic (like SQL UPDATE
statements) you can not define up
and down
methods at the same time.
If you were to define define all 3 of them, Rails would only run change
and ignore up
and down
. However, Rails 4+ features a helper method called reversible
:
class MyMigration < ActiveRecord::Migration
def cha...
Upgrading a Rails 3.2 application to Ruby 2.1 is really easy
Upgrading from Ruby 1.8.7 to 2.1.2 took me an hour for a medium-sized application. It involved hardly any changes except
- removing the occasional monkey patch where I had backported functionality from modern Rubies
- Migrating from
require
torequire_relative
where I loaded RSpec factories in Cucumber'senv.rb
(the Rails application root is no longer in the load path by default) - replacing the old debugger with
byebug
- removing
sytem_timer
from Gemfile (see [this SO thread](http://stackoverflow.com/questions/7850216/how-to-inst...
Using Passenger Standalone for development
For our production servers we use Passenger as a Ruby application server. While it is possible to use Passenger for development as an Apache module, the installation process is not for the faint of heart.
Luckily Passenger also comes as a standalone binary which requires zero configuration.
You can Passenger Standalone as a replacement for Webrick or Thin if you'd like to:
- Use SSL certificates locally
- Get performance behavior that is closer to ...
Bootstrap: How to avoid printing link URLs
By default, Twitter Bootstrap's print styles include printing links.
/* Bootstrap's way of printing URLs */
@media print {
a[href]:after {
content: " (" attr(href) ")";
}
}
If you want to turn that off, you can do
/* Don't print link hrefs */
@media print {
a[href]:after {
content: none
}
}
Angular: Caching API responses in Restangular
Restangular can make use of $http
's built-in response cache.
# Cache response for single request
Restangular.one('accounts', 123).withHttpConfig({ cache: true }).get();
# Cache responses for all requests (be careful with that, you might work with stale data)
RestangularProvider.setDefaultHttpFields({ cache: true });
To invalidate cached responses e.g. on a state change in UI Router, you can do
@app.run ['$rootScope', '$cacheFactory', ($rootScope, $cacheFactory) ->
$rootScope.$on '$stateChangeSuccess', ->
$cacheF...