Add an alternative image source for broken images
Awesome hack by Tim VanFosson:
<img src="some.jpg" onerror="this.src='alternative.jpg'" />
ActiveRecord: Order a scope by descending value without writing SQL
Instead of this:
Image.order('images.created_at DESC')
You can write this:
Image.order(created_at: :desc)
Not only do you not have to write SQL, you also get qualified column names (created_at becomes images.created_at) for free.
Multiple order criteria
To add secondary order criteria, use a hash with multiple keys and :asc / :desc values:
Image.order(title: :asc, created_at: :desc)
PostgreSQL: How to change attributes of a timestamp
It's generally not trivial to change a datetime's seconds, minutes, etc in SQL. Here is how it works when speaking PostgreSQL.
Consider you have a timestamp column whose seconds you want to zero:
SELECT born_at FROM users;
born_at
---------------------
2015-05-01 13:37:42
You can the TO_CHAR function to convert date or time values into a string, and do your changes there:
SELECT TO_CHAR(born_at, 'YYYY-MM-DD HH24:MI:00') FROM users;
to_char
---------------------
2015-05-01 13:37:00
...
Rails has a built-in slug generator
Today I learned that Ruby on Rails has shipped with a built-in slug generator since Rails 2.2:
> "What Up Dog".parameterize
=> "what-up-dog"
> "foo/bar".parameterize
=> "foo-bar"
> "äöüß".parameterize
=> "aouss"
Also see: Normalize characters in Ruby.
Responsive Tables in Pure CSS
Clever hack using data-attributes to assign labels to cells.
It's still a massive duplication of code (labels), but better and more lightweight than most solutions I've seen for this surprisingly tricky problem.
Custom loggers in Ruby and Rails
File logger
If you need to log to a file you can use Ruby's Logger class:
require 'logger'
log = Logger.new('log/mylog.log')
log.info 'Some information'
log.debug 'Debugging hints'
log.error StandardError.new('Something went wrong')
Logger does a number of things well:
- Message type (info / debug / error) is logged
- Log entries are timestamped
- Writing log output is synchronized between threads
- Logged errors are printed with full backtraces
If you don't like the output format, you can define a custom formatter.
I ha...
Dusen (>0.5) now with "exclude from search"
Dusen (our search gem) is now capable of excluding words, phrases and qualified fields from search.
E.g. search for
included -excluded"search this" -"not that"topic:"Yes" -topic:"No"
This will soon also work in makandra cards!
Angular: Fixing "Referencing DOM nodes in Angular expressions is disallowed"
Reason
If you are using Coffeescript, it is likely to be the culprit. Since Coffeescript always returns the value of the last expression, it may return DOM nodes:
# coffeescript
scope.focus = ->
element.focus()
# javascript
scope.focus = function() {
return element.focus(); // wheee
}
If you e.g. use this function like this, the error will be raised:
<span ng-click="focus()">...</span>
Solution
By adding an explicit return value (e.g. return false), you can Coffees...
How to use CSS to rotate text by 90° in IE8 (and modern IEs)
If you want to rotate text, you can use CSS transforms in somewhat modern browsers to rotate the container element.
However, if you need to support IE8, transform is unavailable (if need only IE9 support, ignore the following and use -ms-transform).
Here is a solution that worked for me:
<div class="my-element">Hi!</div>
^
.my-element {
display: inline-block;
transform: rotate(90deg);
-ms-writing-mode: tb-rl;
-ms-transform: none;
}
This way, browsers will use CSS transforms when available -- w...
Communication between collaborating directives in Angular
What if a complicated component comes along that is naturally modeled by multiple directives? This group of directives, as a whole, form a single self contained component. None of directives in the group can stand alone because they only make sense when used together; they collaborate; they are aware of each other and need to communicate with each other.
This post will discuss best practices for managing communication among collaborating directives and illustrate these practices with an example.
Linux: Kill a process matching a partial name
This is useful to kill processes like ruby my-script.rb:
pkill -f my-script.rb
With great power comes great responsibility.
How to enable WebGL in Chrome
Check your GPU state on chrome://gpu. If it reads "WebGL: Hardware accelerated" in the first list, you're set. Else:
- Make sure chrome://flags/#disable-webgl is disabled (there should be a link "Enable")
- If that does not help, try to additionally enable chrome://flags/#ignore-gpu-blacklist.
Angular: Solving "$digest already in progress" error
TL;DR You shouldn't call $scope.$apply() or $scope.$digest() inside a function that can be invoked by Angular – e.g. in an ngClick.
The linked Stackoverflow answer has a quick overview of techniques to apply changes to a scope. It also explains what might be wrong when you're getting the error $digest already in progress and gives some information that every Angular developer should know.
Angular Style Guide
Opinionated Angular style guide for teams by @john_papa
Not everything in this guide works perfectly for us, but is still a good start.
Slack integration for deployments via Capistrano
You can hook into Slack when using Capistrano for deployment. The slackistrano gem does most of the heavy lifting for you. Its default messages are unobtrusive and can be adjusted easily.
When deploying, it posts to a Slack channel like this:
How to integrate
Integrating Slackistrano with Capistrano 3 is fairly simple.
- In your Slack, open menu → A...
Use CSS sibling selectors instead :last-child (or :first-child)
Often times you want to give a bunch of elements the same style, except for the last. For example borders or margins.
You probably commonly used the :last-child CSS meta selector like so:
.foo {
border-bottom: 1px dashed #000;
}
.foo:last-child {
border-bottom-width: 0;
}
However, this only works when an element is the last child of its parent. Any other siblings which are unrelated to your case will break it.
Instead, prefer using the + sibling selector. It applies to the element following the other.
.foo + .foo {
...
Exporting to Excel from Rails without a gem
See this Railscast.
Basically you can simply write views like index.xlsx.erb:
<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<Worksheet ss:Name="Sheet1">
<Table>
<Row>
<Cell><Data ss:Type="String">ID</Data></Ce...
Multiline comments in indented Sass syntax
Write a // and indent every subsequent line by two spaces.
This is great for documenting BEM blocks!
//
An action button
================
Basic usage
-----------
<a href="/path" class="action">New booking</a>
<button class="action">Save</a>
<input type="submit" class="action">Save</a>
Colors
-------
<a href="/path" class="action is-red">Primary</a>
<a href="/path" class="action is-grey">Secondary</a>
Small inline buttons
--------------------
<p>
Recor...
FactoryBot: How to get the class from a factory name
When you want to look up a class for a given factory, do it like this:
>> FactoryBot.factories.find('admin').build_class
=> User
In older versions, you could do:
>> FactoryBot.factory_by_name('admin').build_class
=> User
Speed up file downloads with Rails, Apache and X-Sendfile
When you use the send_file method to send a local file to the browser, you can save resources on the application server by setting the :x_sendfile option to true. This option is activated by default for Rails 3, so you need to understand this.
What this option does is not to send any data at all, but rather set the local file path as a new response header:
X-Sendfile: /opt/www/awesome-project/shared/downloads/image.png
When the response comes back from Rails to...
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...
Fixing jerky CSS3 animations
When a CSS3 animation makes the animated element flicker, it may well be due to pixel fragments being handled differently during animation. You can force the browser into rendering the element on the GPU by adding certain properties. In Chrome, the combination of the following properties has the best effect.
box-shadow: 0 0 0 #000
transform: translate3d(0,0,0) # remember to add vendor prefixes
Depending on your markup, you might need to set these properties on several elements (presumably all those that have height or width in %)...
Sass Mixins vs Extends: The Data - Belly Card Engineering
The debate between using mixins or extends in Sass has been heating up recently. From the surface it appears they both provide solid benefits in helping us write consistent and modular code. However, the critics are out and extends specifically have come under fire. But why?
Interesting results: Although mixins create more code than extends, the gzipped CSS is smaller and somewhat faster to evaluate for current browsers.