How to split up a git commit
Quick steps
-
git rebase -i
-> mark your commit withedit
-
git reset HEAD~
(remove the marked commit, but keep its changes) - Make several commits (optionally setting the previous author manually)
git rebase --continue
Detailed instructions
Basically, you will review the last n
commits and stop at the splittable commit. Then you'll undo that commit and put its changes into new commits at your liking.
-
Review commits (
rebase
)git rebase -i HEAD~3 # or git rebase -i origin/master
...
Shorthand function properties in ES6
Here is an ES5 object literal with two string properties and a function property:
let user = {
firstName: 'Max',
lastName: 'Muster',
fullName: function() { return this.firstName + ' ' + this.lastName }
}
user.fullName() // => 'Max Muster'
In ES6 we can define a function property using the following shorthand syntax:
let user = {
firstName: 'Max',
lastName: 'Muster',
fullName() { return this.firstName + ' ' + this.lastName }
}
user.fullName() // => 'Max Muster'
We can also define a gette...
nvm: Setting a default Node.js version
To set a default Node version for new shells, use nvm alias default <VERSION>
:
nvm alias default 1.2.3
I like to use the most recent LTS version as my default:
nvm alias default lts/erbium
Rails Partials
Rails partials have a lot of "hidden" features and this card describes some non-obvious usages of Rails Partials.
Rendering a basic partial
The most basic way to render a partial:
render partial: 'partial'
This will render a _partial.html.erb
file. Notice how all partials need to be prefixed with _.
It's possible to define local variables that are only defined in the partial template.
# _weather.html.erb
<h1>The weather is <%= condition %></h1>
# index.html.erb
render partial: 'weather', locals: { condition: ...
Heads up: Deployment with newly generated SSH key (using ED25519) might fail
If you use a newer SSH key generated with the ED25519 algorithm instead of RSA (see Create a new SSH key pair), the deployment with Capistrano may fail with the following message:
The deploy has failed with an error: unsupported key type `ssh-ed25519'
net-ssh requires the following gems for ed25519 support:
* ed25519 (>= 1.2, < 2.0)
* bcrypt_pbkdf (>= 1.0, < 2.0)
See https://github.com/net-ssh/net-ssh/issues/565 for more information
Gem::LoadError : "ed25519 i...
Issue Checklist Template
This is a checklist I use to work on issues. For this purpose I extracted several cards related to the makandra process and ported them into a check list and refined that over time a little bit.
This task list is divided by the Gate keeping process in the following steps:
1. Starting a new feature
2. Working on the issue
3. Finishing a feature
4. After Review
Here are some ti...
Linux: Open a file with the default application
If you are on a Linux shell and want to open a file with whatever default application is configured for that type, this often works:
xdg-open Quote.odt
xdg-open invoice.pdf
xdg-open index.html
Pro Tip
Make an alias so you have a simpler API (like Mac OS): alias open=xdg-open
or alias x=xdg-open
.
Background
You can choose your "Default applications" via UI in the Ubuntu "Settings" application (gnome-control-center
). This is just a very rough setting (e.g. open Photos with Shotwell Viewer).
If a certain file...
Manipulate color with Sass functions
Sass comes with many built-in functions to manipulate color. Some of the more interesting functions include:
adjust-hue($color, $degrees)
Changes the hue of a color.
lighten($color, $amount)
Makes a color lighter.
darken($color, $amount)
Makes a color darker.
saturate($color, $amount)
Makes a color more saturated.
desaturate($color, $amount)
Makes a color less saturated.
grayscale($color)
Converts a color to grayscale.
complement($color)
Returns the compleme...
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...
Rails: Using database default values for boolean attributes
In the past we validate and set default values for boolean attributes in Rails and not the database itself.
Reasons for this:
- Older Rails didn't support database defaults when creating new records
- Application logic is "hidden" in the database
An alternative approach, which currently reflects more the general opinion of the Rails upstream on constraints in the database, is adding default values in the schema of the database itself. We also ...
HTTP headers can only transport US-ASCII characters safely
HTTP header values must only contain low-ASCII (7-bit) characters for safe transport. From RFC 7230:
Historically, HTTP has allowed field content with text in the ISO-8859-1 charset [ISO-8859-1], supporting other charsets only through use of [RFC2047] encoding. In practice, most HTTP header field values use only a subset of the US-ASCII charset [USASCII]. Newly defined header fields SHOULD limit their field values to US-ASCII octets.
If you need to transport 8-bit+ characters (e.g...
Configuring RubyGems to not install documentation by default
When installing gems, a lot of time is spent building locally installed documentation that you probably never use.
We recommend you disable documentation generation for gem install
by default.
Note that Bundler won't install documentation, so this advice applies only when installing gems manually.
If you don't already have it, create a ~/.gemrc
file. The gemrc is a Yaml file, so add the following line to add default switches to the gem
command.
gem: --no-document
(If you do n...
ActiveRecord: count vs size vs length on associations
TL;DR: You should generally use #size
to count associated records.
size
- Counts already loaded elements
- If the association is not loaded, falls back to a
COUNT
query
count
- If a counter cache is set up, returns the cached value
- Issues a
COUNT
query else
Caveats
- If you trigger a
COUNT
query for an association of an an unsaved record, Rails will try to load all children where the foreign keyIS NULL
. This is not what you want. To prevent this behavior, you can useunsaved_record.association.to_a.size
. - `c...
HTTP Client in RubyMine
RubyMine has a HTTP Client that can be useful to test web APIs.
Just create a .http
scratch file an write your request in it.
The request can then be executed with the "Run all requests in File" button above the file.
Some alternatives:
The format for request is like this:
Method Request-URI HTTP-Version
Header-field: Heade...
How to turn images into inline attachments in emails
Not all email clients support external images in all situations, e.g. an image within a link. In some cases, a viable workaround is to turn your images into inline attachments.
Note
Rails provides a simple mechanism to achieve this:
This documentation makes it look like you have to care about these attachments in two places. You have to create the attachment in t...
Carrierwave: Custom file validations inside custom Uploaders
Carrierwave's BaseUploader
can have some validations that you can use by overriding a certain method, which's expected name is hard coded. A popular example is extension_allowlist
, which returns an array of strings and let's you only upload files that have a filename with an extension that matches an entry in that array. Another useful validation can be size_range
, which gives you a little bit of control over how your storage gets polluted.
This is often good enough, but some times you need to validate special cases.
Validations t...
Rails: Encrypting your database information using Active Record Encryption
Since Rails 7 you are able to encrypt database information with Active Record. Using Active Record Encryption will store an attribute as string in the database. And uses JSON for serializing the encrypted attribute.
Example:
-
p
: Payload -
h
: Headers -
iv
: Initialization Vector -
at
: Authentication Tag
{ "p": "n7J0/ol+a7DRMeaE", "h": { "iv": "DXZMDWUKfp3bg/Yu", "at": "X1/YjMHbHD4talgF9dt61A=="} }
Note this before encrypting attributes with Active Record:
...
How to view a file from another branch
Just run git show branch:file
. Examples:
git show HEAD~:bin/command
git show origin/master:../lib/version.rb
When you want to format only line breaks, you probably do not want `simple_format`
For outputting a given String in HTML, you mostly want to replace line breaks with <br>
or <p>
tags.
You can use simple_format
, but it has side effects like keeping some HTML.
If you only care about line breaks, you might be better off using a small, specialized helper method:
def format_linebreaks(text)
safe_text = h(text)
paragraphs = split_paragraphs(safe_text).map(&:html_safe)
html = ''.html_safe
paragraphs.each do |paragraph|
html << content_tag(:p, paragraph)
end
html
end
Full di...
git: find the version of a gem that releases a certain commit
Sometimes I ran across a GitHub merge request of a gem where it was not completely obvious in which version the change was released. This might be the case for a bugfix PR that you want to add to your project.
Git can help you to find the next git tag that was set in the branch. This usually has the name of the version in it (as the rake release
task automatically creates a git tag during release).
git name-rev --tags <commit ref>
Note
The more commonly used
git describe
command will return the last tag before a c...
Rails: Accessing helper methods from a controller
In Rails 5+ you can access a helper from a controller using the helpers
method:
# Inside a controller action
helpers.link_to 'Foo', foo_path
In older Rails versions you can use view_context
instead:
# Inside a controller action
view_context.link_to 'Foo', foo_path
Preloaded associations are filtered by conditions on the same table
When you eagerly load an association list using the .include
option, and at the same time have a .where
on an included table, two things happen:
- Rails tries to load all involved records in a huge single query spanning multiple database tables.
- The preloaded association list is filtered by the
where
condition, even though you only wanted to use thewhere
condition to filter the containing model.
The second case's behavior is mostly unexpected, because pre-loaded associations usually don't care about the circumstances under whi...
ActiveRecord: Specifying conditions on an associated table
We can use ActiveRecord's where
to add conditions to a relation. But sometimes our condition is not on the model itself, but on an associated model. This card explains multiple ways to express this condition using ActiveRecord's query interface (without writing SQL).
As an example we will use a User
that has many Post
s:
class User < ApplicationRecord
has_many :posts
scope :active, -> { tra...
Generating test images on the fly via JavaScript or Ruby
When you need test images, instead of using services like lorempixel or placehold.it you may generate test images yourself.
Here we build a simple SVG image and wrap it into a data:
URI. All browsers support SVG, and you can easily adjust it yourself.
Simply set it as an image's src
attribute.
JavaScript
Simple solution in modern JavaScript, e.g. for use in the client's browser:
function svgUri(text) {
let svg = `
<svg wid...