Get the last leaf of a DOM tree (while considering text nodes)
I use this to simulate the (non-existing) :last-letter
CSS pseudoclass, e. g. to insert a tombstone at the end of an article:
findLastLeaf = ($container) ->
$children = $container.children()
if $children.length == 0
$container
else
$lastChild = $children.last()
$lastContent = $container.contents().filter(->
# Only return nodes that are either elements or non-empty text nodes
@nodeType == 1 || (@nodeType == 3 && _.strip(@nodeValue) != '')
).last()
...
Chrome 34+, Firefox 38+, IE11+ ignore autocomplete=off
Since version 34, Chromium/Chrome ignores the autocomplete="off"
attribute on forms or input fields. Recent versions of other browser do the same, although implementation details vary.
This is especially problematic for admin areas because Chrome might automatically fill in a password on a "add new user" forms.
Chrome developers say this is by design as they believe it encourages users to store more complex passwords.
Recommended fix for Chrome and F...
About "unexpected '#' after 'DESCENDANT_SELECTOR' (Nokogiri::CSS::SyntaxError)"
The error unexpected 'x' after 'DESCENDANT_SELECTOR' (Nokogiri::CSS::SyntaxError)
(where x
may be basically any character) occurs when the Nokogiri parser receives an invalid selector like .field_with_errors #
or td <strong>
.
In Cucumber, the culprit will be an invalid step definition that builds an invalid selector:
# inside some step definition:
field = find_field(label)
page.send(expectation, have_css(".field_with_errors ##{field[:id]}"))
The above raises the mentioned error if field[:id]
is nil, i.e. the foun...
YAML: Keys like "yes" or "no" evaluate to true and false
If you parse this Yaml ...
yes: 'Totally'
no: 'Nope'
... you get this Ruby hash:
{ true: 'Totally',
false: 'Nope' }
In order to use the strings 'yes' and 'no' as keys, you need to wrap them with quotes:
'yes': 'Totally'
'no': 'Nope'
There's actually a long list of reserved words with this behavior:
y|Y|yes|Yes|YES|n|N|no|No|NO
|true|True|TRUE|false|False|FALSE
|on|On|ON|off|Off|OFF
I'm sorry.
Fix Rubygems error: undefined method `source_index' for Gem:Module
You are probably using Ruby 1.8.7 with a too recent versions of Rubygems.
Downgrade your Rubygems to the latest version that works with 1.8.7.
See also
- Fix Rubygems warning: Gem.source_index is deprecated, use Specification
- Fix Rubygems binary error: undefined method `activate_bin_path' for Gem:Module (NoMethodError)
- [Bundler: Gemfile.lock is corrupt & gems are missing from the DEP...
OpenStack nova resize "ERROR: Resize requires a change in size"
If you get this error when you try to resize an OpenStack instance:
# nova resize example 23 --poll
ERROR: Resize requires a change in size. (HTTP 400)
You need to change your flavor to have a different memory size. It's a bug in an older OpenStack version:
# /nova/compute/api.py
if (current_memory_mb == new_memory_mb) and flavor_id:
raise exception.CannotResizeToSameSize()
which got fixed 2012-09-12 ([https://git.openstack.org/cgit/openstack/nova/commit/nova/compute/api.p...
Bash output redirection
There are 3 built-in file descriptors: stdin, stdout and stderr (std=standard). (You can define your own, see the linked article.)
Basic
-
0
/1
/2
references stdin/stdout/stderr -
>
/2>
redirects stdout/stderr, where>
is taken as1>
-
&1
/&2
references stdout/stderr -
&>
redirects stdout and stderr = everything (caution: see below)
Caution: &>
is functional as of Bash 4. This seems to result in a slightly differing behaviour when redirecting output in Ru...
Strong params: Raise in development if unpermitted params are found
Rails 4:
config.action_controller.action_on_unpermitted_parameters
enables logging or raising an exception if parameters that are not explicitly permitted are found. Set to :log
or :raise
to enable. The default value is :log
in development and test environments, and false in all other environments.
Rails 3:
If you include the strong_params
gem, see the Readme for handling unpermitted keys.
Mute Rails asset pipeline log messages
quiet_assets
helps with disabling asset pipeline log messages in the development log. When the gem is added, asset pipeline logs are suppressed by default.
If you want to disable muting temporarily, add config.quiet_assets = false
to your config/application.rb
.
Making media queries work in IE8 and below
When using @media
CSS queries, Internet Explorer 8 and below will fail to respect them.
Though there are several options (like mediatizr
and css3-mediaqueries
), Respond.js was the only one that worked for me.
If you do not want to pollute your application's default JS file with Respond.js, simply:
-
Create an extra JS file (like
media_queries_polyfill.js
) that loads Respond.js://= require respond-1.4.2
-
Make sure it's added to
config.assets.precompile
-
Embed that JS fi...
Spreewald: Old-school cucumber steps, freshly pickled
Cucumber_rails' old-school web-steps have been deprecated for a while, urging developers to write high-level step definitions that directly use Capybara or Webrat.
We think that's a bit drastic. More high-level steps are good, but ticking the odd check box with a general step is not always bad.
So we took the old web steps, improved them a bit, added some other favorites of ours (steps for emails, tables, [time travelling](/ma...
Disabling HSTS
If you once had HTTP Strict Transport Security enabled for a domain, and you want to disable it again, you need to send this header over a secure connection:
Strict-Transport-Security: max-age=0;
The next time a browser visits your site, it will forget that it was once flagged as HTTPS-only.
Should you need to remove the HSTS flag from your local browser (e.g. for debugging), you can do so in Chrome by accessing [chrome://net-internals/#hsts](chrome://net-internals/#hs...
Retrieving the class an ActiveRecord scope is based on
Edge Rider gives your relations a method #origin_class
that returns the class the relation is based on.
This is useful e.g. to perform unscoped record look-up.
Post.recent.origin_class
# => Post
Note that #origin_class
it roughly equivalent to the blockless form of #unscoped
from Rails 3.2+, but it works consistently across all Rails versions. #unscoped
does not exist for Rails 2 and is broken in Rails 3.0.
Why you might not need MVC with React.js
React.js is a relatively new Javascript templating engine that has two-way-bindings like AngularJS or Batman. The interesting idea here is that React keeps a virtual copy of the DOM tree in memory, and when you re-render, it only changes the DOM as little as required. That means if you re-render a list with 1000 items, and only one item has changed, the browser-DOM will only remove and add a single element instead of 1000 elements. This makes React.js views insanely fast.
The attached article proposes that React.js is so fast that you don...
Disabling Spring when debugging
Spring is a Rails application preloader. When debugging e.g. the rails
gem, you'll be wondering why your raise
, puts
or debugger
debugging statements have no effect. That's because Spring preloads and caches your application once and all consecutive calls to it will not see any changes in your debugged gem.
Howto
Disable spring with export DISABLE_SPRING=1
in your terminal. That will keep Spring at bay in that terminal session.
In Ruby, [you can only write environment variables that subproc...
Offtopic: Floppy-disc OS
MenuetOS is an Operating System in development for the PC written entirely in 32/64 bit assembly language. Menuet64 is released under License and Menuet32 under GPL. Menuet supports 32/64 bit x86 assembly programming for smaller, faster and less resource hungry applications.
- Fits on a single floppy, boots also from CD and USB drives
- Responsive GUI with resolutions up to 1920x1080, 16 million colours
- Free-form, transparent and skinnable application windows, drag'n drop
- SMP multiprocessor support with currently up to 8 cpus
- IDE: E...
How to create Rails Generators (Rails 3 and above)
General
- Programatically invoke Rails generators
-
Require the generator, instantiate it and invoke it (because generators are
Thor::Group
s, you need to invoke them withinvoke_all
). Example:require 'generators/wheelie/haml/haml_generator' Generators::HamlGenerator.new('argument').invoke_all
Other ways: Rails invokes its generators with
Rails::Generators.invoke ARGV.shift, ARGV
. From inside a Rails generator, you may call the [inherited Thor methodinvoke(args=[], options={}, config={})
](https://github...
docopt: A promising command line parser for (m)any language
docopt helps you define interface for your command-line app, and automatically generate parser for it.
docopt is based on conventions that are used for decades in help messages and man pages for program interface description. Interface description in docopt is such a help message, but formalized. Here is an example:
Naval Fate.
Usage:
naval_fate ship new <name>...
naval_fate ship <name> move <x> <y> [--speed=<kn>]
naval_fate ship shoot <x> <y>
naval_fate mine (set|remove) <x> <y> [--moored|--drifting]
naval_fate -h |...
Ruby Exception Class Hierarchy
This note summarizes the ruby exception hierarchy.
Exception
NoMemoryError
ScriptError
LoadError
NotImplementedError
SyntaxError
SignalException
Interrupt
Timeout::Error # < ruby 1.9.2
StandardError # caught by rescue (default if no type was specified)
ArgumentError
IOError
EOFError
IndexError
LocalJumpError
NameError
NoMethodError
Ran...
Sticky table header with jQuery
When you want the table headers to always stay around (e.g. because that table is huuuge), use the code below.
Style
table.fixed_table_header{
position: fixed;
top: 0;
width: auto;
display: none;
border: none;
margin: 0;
}
Javascript
;(function($) {
$.fn.fixHeader = function() {
return this.each(function() {
var $table = $(this),
$t_fixed;
function init() {
$t_fixed = $table.clone();
$t_fixed.find('tbody').remove().end().addClass('fi...
Hash any Ruby object into an RGB color
If you want to label things with a color but don't actually care which cholor, you can use the attached Colorizer
class.
To get a completely random color (some of which will clash with your design):
Colorizer.colorize(some_object) # => "#bb4faa"
To get similiar colors (e. g. bright, pale colors of different hues):
# random hue, saturation of 0.5, lightness of 0.6
Colorizer.colorize_similarly(some_object, 0.5, 0.6) # => "#bbaaaa"
Also see the color gem.
Restangular: How to remove an element from a collection without breaking restangular
So you have a restangular collection and you want to remove an element from it, after you've successfully deleted it from the server.
The README suggests to say something like $scope.users = _.without($scope.users, user)
. While that works at first glance (the element is no longer in your collection), it will break horribly when you want to use restangular's attributes on that collection.
This...
better rails app restart with the passenger restart-app tool
With this command you can initiate an application restart without touching restart.txt. Unlike touching restart.txt, this tool initiates the restart immediately instead of on the next request. http://blog.phusion.nl/2014/01/02/phusion-passenger-4-0-33-released/
If you want to use this with capistrano 2.x just replace the touch command:
- run "touch #{current_path}/tmp/restart.txt"
+ run "passenger-config restart-app --ignore-app-not-running #{deploy_to}...
Rails 2: Refuse response formats application-wide
If you regularly get ActionView::MissingTemplate
exceptions, maybe some bot visits your site requesting silly formats like:
http://www.rails-app.com/makandra.html-username-2000 # => Rails tries to retrieve 'makandra' with format 'html-username-2000'
Just restrict accepted format parameters for the whole application like this:
class ApplicationController < ActionController::Base
before_filter :refuse_silly_formats
private
def refuse_silly_formats
acceptable_formats = %w[html xml pdf]
if par...