Async/Await Will Make Your Code Simpler
Sometimes modern Javascript projects get out of hand. A major culprit in this can be the messy handling of asynchronous tasks, leading to long, complex, and deeply nested blocks of code. Javascript now provides a new syntax for handling these operations, and it can turn even the most convoluted asynchronous operations into concise and highly readable code.
JavaScript: How to query the state of a Promise
Native promises have no methods to inspect their state.
You can use the promiseState
function below to check whether a promise is fulfilled, rejected or still pending:
promiseState(promise, function(state) {
// `state` now either "pending", "fulfilled" or "rejected"
});
Note that the callback passed to promiseState
will be called asynchronously in the next [microtask](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/...
Vagrant: create entry for box in .ssh/config
If you want to ssh into your vagrant box without switching into the project directory and typing vagrant ssh
, you can also create an entry directly in ~/.ssh/config
. This will allow you to use ssh <my-box>
from anywhere. Simply paste the information provided by vagrant ssh-config
to your ~/.ssh/config
-File: vagrant ssh-config >> ~/.ssh/config
Example:
$ vagrant ssh-config
Host foobar-dev
HostName 127.0.0.1
User vagrant
Port 2200
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
Id...
How to install a current version of git to your Ubuntu machine
As described by the linked Stackoverflow answer, run these commands:
sudo add-apt-repository ppa:git-core/ppa -y
sudo apt-get update
sudo apt-get install git
git --version
This will get you Git 2.6.4 (as of Dec 2015).
Troubleshooting
If you don't have add-apt-repository
yet, install it with:
sudo apt-get install python-software-properties software-properties-common
Understanding Scope in Ruby
Scope is all about where something is visible. It’s all about what (variables, constants, methods) is available to you at a given moment. If you understand scope well enough, you should be able to point at any line of your Ruby program and tell which variables are available in that context, and more importantly, which ones are not.
The article gives detailed explanation on the variable scope in ruby with examples that are easy to understand. Every ruby developer should at least know the first part of the article by heart. The second half ...
JavaScript: Polyfill native Promise API with jQuery Deferreds
You should prefer native promises to jQuery's Deferreds. Native promises are much faster than their jQuery equivalent.
Native promises are supported on all browsers except IE <=11, Android <= 4.4 and iOS <= 7.
If you need Promise
support for these old browsers y...
murdho/rack-cargo: Batch requests for Rack APIs
rack-cargo gives your API a new /batch
route that lets clients perform multiple API calls with a single request.
The batched calls are resolved internally and are then returned as an array of responses:
// This is batch request payload:
{
"requests": [
{
"name": "order",
"path": "/orders",
"method": "POST",
"body": {
"address": "Home, 12345"
}
},
{
"name": "order_item",
...
travisliu/traim: Resource-oriented microframework for RESTful APIs
Use Traim to build a RESTful API for your ActiveRecord models with very little code.
Traim assumes your API resources will map 1:1 to your ActiveRecord models and database tables. This assumption usually falls apart after a few months into a project, so be ready to replace your Traim API with something more expressive afterwards.
Traim outputs a Rack application which you can either serve standalone or mount into your Rails app.
Deleting stale Paperclip attachment styles from the server
Sometimes you add Paperclip image styles, sometimes you remove some. In order to only keep the files you actually need, you should remove stale Paperclip styles from your server.
This script has been used in production successfully. Use at your own risk.
# Config #######################################################################
delete_styles = [:gallery, :thumbnail, :whatever]
scope = YourModel # A scope on the class with #has_attached_file
attachment_name = :image # First argument of #has_attached_file
noop ...
ActiveRecord: How to use ActiveRecord standalone within a Ruby script
Re-creating a complex ActiveRecord scenario quickly without setting up a full-blown Rails app can come in handy e.g. when trying to replicate a presumed bug in ActiveRecord with a small script.
# Based on http://www.jonathanleighton.com/articles/2011/awesome-active-record-bug-reports/
# Run this script with `$ ruby my_script.rb`
require 'sqlite3'
require 'active_record'
# Use `binding.pry` anywhere in this script for easy debugging
require 'pry'
# Connect to an in-memory sqlite3 database
ActiveRecord::Base.establish_connection(
ad...
IRB: last return value
In the ruby shell (IRB) and rails console the return value of the previous command is saved in _
(underscore). This might come in handy if you forgot to save the value to a variable and further want to use it.
Example:
irb(main):001:0> 1 + 2
=> 3
irb(main):002:0> _
=> 3
irb(main):003:0> a = _
=> 3
ImageMagick: How to auto-crop and/or resize an image into a box
Auto-cropping
ImageMagick can automatically crop surrounding transparent pixels from an image:
convert input.png -trim +repage output.png
You need to +repage
to update the image's canvas, or applications will be randomly confused.
Trimming specific colors is also possible, see the documentation.
Resizing into a box
Occasionally, you want to resize an image to a maximum width or height, and change the "outer" image dimensions to something that won't match the input image.
To re...
RSpec's hash_including matcher does not support nesting
You can not use the hash_including
argument matcher with a nested hash:
describe 'user' do
let(:user) { {id: 1, name: 'Foo', thread: {id: 1, title: 'Bar'} }
it do
expect(user).to match(
hash_including(
id: 1, thread: {id: 1}
)
)
end
end
The example will fail and returns a not very helpful error message:
expected {:id => 1, :name => "Foo", :thread => {:id => 1, :title => "Bar"}} to...
Guide: How to use our (maybe in future) default rubocop config
Follow the instructions here.
PRs at makandra/rubocop-config are welcome. Also check the issue tracker.
RubyMine
Since version 2017-1 RubyMine runs cops in the background, and displays RuboCop offenses the ...
Know what makes your browser pant
I figure we needed a definitive reference for what work is triggered by changing various CSS properties. It's something I get asked about often enough by developers, and while we can do tests with DevTools, I have both the time and inclination to shortcut that for everyone. I'm nice like that. —Paul Lewis
ActiveRecord::RecordNotFound errors allow you to query the :name and :id of the model that could not be found
ActiveRecord::RecordNotFound
errors provide quite meaningful error messages that can provide some insight on application details. Consider the following:
ActiveRecord::RecordNotFound: Couldn't find Organisation::Membership with 'id'=12 [WHERE "organisation_memberships"."user_id" = 1]
You should probably not simply render those error messages to the user directly. Instead you you might want to re-raise your own errors. ActiveRecord::RecordNotFound
provides you with methods :model
and :id
where you can get information about w...
Rails: wrap_parameters for your API
Rails 5 (don't know about the others) comes with an initializer wrap_parameters.rb
. Here you can tell rails to wrap parameters send to your controllers for specific formats into a root node which it guesses from the controller name.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json]
end
This would wrap a flat json body, like
{"name": "Konata"}
that gets send to your UsersController
into
{"name" => "Konata", "user" => {"name" => "Konata"}}
Note that the params are now duplicat...
Rails: Configure ActionController to raise when strong params are invalid
Put the line below in the respective env.rb
file to make your action controllers raise an ActionController::UnpermittedParameters
error when strong params are not valid. This might come in handy when you are implementing an API and you want to let the user know that the request structure was invalid. You can then rescue those errors by implementing a rescue_from
to have a generic handling of those cases. Note that you might need to whitelist common params such as :format
to not raise on valid requests.
config.action_controller.a...
Selenium cannot obtain stable Firefox connection
When using geordi for integration tests you might get the following error when trying to run geordi cucumber
:
unable to obtain stable firefox connection in 60 seconds (127.0.0.1:7055) (Selenium::WebDriver::Error::WebDriverError)
This means, that the vnc window the tests is talking to has no proper firefox version running. To figure out the issue this might help you:
- Check if the
.firefox-version
(e.g.24.0
) is the same as~/bin/firefoxes/24.0/firefox
says in the browser - Maybe [rest...
How to: Snom 300 firmware update
First, go to the webinterface of your phone.
Choose Software Update
in the navigation on the left.
Next, you have to find the current firmware version for your model in the snom wiki. To do this, you have to follow the ?
next to the Firmware
text field to this page and then follow the link of the current firmware below Firmware Versions
in the wiki. Now select your phone model. Next you have to choose between the minor versions. Follow the link of the most recent stable versio...
Snom 300 with headset: Unlink ringtone volume from headset volume
If your Snom 300 always keeps the same volume for headset and ringtone (as soon as you change one you also change the other), here's what to do:
Go to your phone settings web interface, then Preferences
(German Präferenzen
). There is the seemingly harmless setting for Ringer Device from Headset
(German Klingeltonausgabe bei Kopfhörer
). Choose one: "Headset" or "Speaker". Do not select both, otherwise the ringtone volume will always be the same as the headset speaker volume!
Ubuntu: Share internet connections with other computers
You can configure a Ubuntu system as a gateway in order to share it's internet connection (maybe via WLAN or tethering) with other computers on the network.
On the gateway
- Enable ip traffic forwarding:
-
Open
/etc/sysctl.conf
-
Uncomment the line
net.ipv4.ip_forward=1
-
Reload using
sudo sysctl -p /etc/sysctl.conf
-
- Reconfigure ip_tables to allow NAT:
- Download the attached file
- Replace
online_device
with the name of the network device that provides the internet connection
...
How to make select2 use a Bootstrap 4 theme
select2 is a great jQuery library to make (large) <select>
fields more usable.
For Bootstrap 3 there is select2-bootstrap-theme.
It won't work for Bootstrap 4, but rchavik's fork does (at least with Bootstrap 4 Alpha 6, current version at time of writing this).
It is based on a solution by angel-vladov and adds a few fixes.
Use it by addi...
Capistrano: Doing things on rollback
Capistrano has the concept of a "rollback" that comes in really handy in case of errors. When you notice that your recent deploy was faulty, run cap deploy:rollback
and you're back with the previous release. In case of an error during a deployment, Capistrano will rollback itself.
But, you may ask, how can it know how to revert all the custom stuff I'm doing during deployment? It can't. But you can tell it how to.
Capistrano 3
Deploy and rollback are nearly identi...