How to mirror a git repo to a new remote
Say you want to move a git repository from one remote (perhaps Github) to another (perhaps Gitlab).
If you have the repo checked out, you still should make sure to mirror all branches of the old remote, not only those you happen to have checked our. Otherwise the target repo will become a copy of your current repo, and not the source repo, potentially missing commits. You can use this:
git remote rename origin old-origin
git remote add origin <new-remote>
git fetch old-origin --prune
git push --prune origin +refs/remotes/old-origin/*:r...
How to: Run webpack dev server with vcap.me
If your Rails application is using Webpack you need to serve assets on the same host as you application runs, otherwise you will see the following errors in your browser console:
[WDS] Disconnected!
Invalid Host header
So if you are using awesome.vcap.me:3000 you need to start the webpack-dev-server with a different host than localhost (0.0.0.0):
bin/webpack-dev-server --host awesome.vcap.me
Capybara: A step for finding images with filename and extension
This cucumber step is useful for testing an image (looking at the src of the image).
Then(/^I should see the image "([^"]*)"$/) do |filename_with_extension|
expect(page).to have_css("img[src*='#{filename_with_extension}']")
end
Then I should see the image "placeholder.png"
Outline: Read more about how to test a uploaded file here, e.g. file downloads.
How to debug Rails autoloading
ActiveSupport::Dependencies takes care of auto-loading any classes in development. This is usually useful, but when you run into issues with the Rails autoloader, you should take a look at what it's doing.
For me this was useful in an "exciting" case of auto-loading classes inside a thread which caused the application to stop responding.
Rails 4.x
ActiveSupport::Dependencies includes logging support. It is easy to use:
ActiveSupport::Dependencies.logger = Rails.logger
Rails 5+
[Logging support was removed](https://github...
PostgreSQL: How to UPDATE multiple attributes with multiple joins
This is an extension to PostgreSQL vs MySQL: How to UPDATE using a JOIN.
UPDATE employees
SET department_name = departments.name,
department_area = areas.name
FROM departments, areas
WHERE employees.department_id = departments.id
AND departments.id = areas.department_id
About-Payments: Platform to compare payment providers
About-Payments is here to help you to accept payments online and
find the best payment service provider for your e-commerce business.
Sprites with Compass
Using CSS sprites for background images is a technique for optimizing page load time by combining smaller images into a larger image sprite.
There are ongoing arguments on how useful this still is, as modern browsers become more comfortable to load images in parallel. However, many major websites still use them, for example amazon, [facebook](...
How to query PostgreSQL's json fields from Rails
PostgreSQL offers a really handy field type: json. You can store any JSON there, in any structure.
While its flexibility is great, there is no syntactic sugar in Rails yet. Thus, you need to manually query the database.
Demo
# Given a Task model with 'details' json column
Task.where("details->>'key' = ?", "value") # matches where 'details' contains "key":"value"
Task.where("details->>'{a,b}' = ?", "value") # matches where 'details' contains "a":{"b":"value"}
Task.where("details->'a'->>'b' = ?", "value") # same as above, but vi...
Font Awesome 5 migration guide
Font Awesome version 5 changed some icon names, and introduces new prefixes fab, far, and fas.
There is a JavaScript shim that you can use as a "quick fix". It allows you to keep v4 icon names on v5.
The linked page includes details on using that, and a migration guide including a list of icon renames.
RSpec: How to check that an ActiveRecord relation contains exactly these elements
To check which elements an ActiveRecord relation contains use the contain_exactly matcher.
describe User do
let!(:admin) { create(:user, role: 'admin') }
let!(:customer) { create(:user, role: 'customer') }
subject(:users) { User.where(role: 'admin') }
# Recommended (The error output is most helpful)
it { expect(users).to contain_exactly(admin) }
# Other options
it { expect(users).to eq([admin]) }
it { expect(users.pluck(:id).to eq([admin.id]) }
end
In case you have an `ActiveRecord::AssociationRelati...
jQuery: How to attach an event handler only once
With "attaching an event handler once" you possibly mean one of these two things:
Register a function for an event, and discard it once that event has happened
Use one instead of on.
$(element).one('eventName', function() { ... });
It has the same API has on.
When code is run multiple times that registers a function for an event, do that only once
With jQuery, you can de-register callbacks. You can use that to achieve registering a function only once.
function myAction() { ... }; // defined somewhere globally o...
Ruby: control flow with throw and catch
This article will show you how to use throw and catch. It's a nice tool to break out of multiple loops when a result is obtained.
Also see our card Ruby: A small summary of what return, break and next means for blocks.
Form letters with LibreOffice Writer
This is painful. Consider using Microsoft Office or switching careers. If you need to write < 20 letters consider doing it manually.
So you didn't listen and here it comes:
- Ignore the Mail Merge Wizard. It will crash or destroy your document.
- Export your addresses, recipient names, etc. as a
.odsspreadsheet (.xls,.xlsx,.ods). Use any columns that work for you, but be consistent. I like to use one column for the address, one column for the salutation line. - Import the spreadsheet as an address book source: *Tools => Add...
Error during Rails 5 upgrade: Environment data not found in the schema
This error is raised because your old database does not have a configured environment yet, which Rails 5 enforces.
If this error occurs while migrating your parallel test databases, make sure to update the parallel_tests gem first: current versions fix this. If you're still using Cucumber < v3, the latest version of parallel_tests will be 2.18.0.
Remember: LoDash syntax is a bit different from UnderscoreJS
Since we are using LoDash instead of UnderscoreJS in recent/current projects, you should keep in mind that their syntax is a bit different.
UnderscoreJS
In UnderscoreJS, methods always return a value:
x = [1, 2, 2]
_.uniq(x) // => [1, 2]
_(x).uniq() // => [1, 2]
If you want to chain multiple calls, you need to start off with a _.chain, and call value() to terminate the chain.
_.chain(x).uniq().map(function(i) { return i + 10 }).reverse().value() // => [12, 11]
##...
How to find and replace empty cells in Libre Office Calc
To find and replace (CTRL + H) empty cells in Libre Office Calc you can use a regular expressions (also called "Finds an empty paragraph" in context of a spreadsheet):
It is also possible to just enter a regular expression in the search (CTRL + F), but there is no option to only search in the current selection like in the screenshot above. Use find and replace instead if needed.
How to use cookies with curl
When making requests using curl, no cookies are sent or stored by default.
However, you can tell curl to re-use cookies received earlier (or forge your own cookies).
There are 2 command line switches you need to use:
-
-cwill write cookies to a given file -
-bwill read cookies from a given file
Example
The remote server sets a "foo" cookie to value "bar". We tell curl to store them to a file at /tmp/cookies using the -c switch.
$ curl -c /tmp/cookies http://httpbin.org/cookies/set?foo=bar
You may look at the file, ...
Rails: Migration helper for inserting records without using models
You should avoid using application models in your migrations. But how else could you create records in a migration?
The most basic way is to write plain SQL, but since INSERT statements are no pleasant write for Rubyists, here is a simple wrapper:
Record creation helper for migrations
The helper method below takes a table name and a hash of attributes, which it inserts into the specified table. Copy it over to your migration and profit!
private
def insert_record(table, **attributes)
attributes.merge!...
CSS: Giving text lines a background-color (with configurable line padding and margin)
The gist is:
- wrap the text with a
span - use
line-heightfor the spacing between lines ("margin") - use
box-shadowto control the line background size ("padding")
Example
span
box-shadow: 0 0 0 10px #fff
background-color: #fff
box-decoration-break: clone # Fix Firefox
line-height: 2.2
→ [jsfiddle](https://jsfiddle.net/2fmqgbh...
Jasmine: Expecting objects as method invocation arguments
To check if a method has been called in Jasmine, you first need to spy on it:
let spy = spyOn(window, 'alert')
codeThatAlerts()
expect(window.alert).toHaveBeenCalledWith('Important message')
To expect an object of a given type, pass the constructor function to jasmine.any():
expect(spy).toHaveBeenCalledWith(jasmine.any(Object))
expect(spy).toHaveBeenCalledWith(jasmine.any(String))
expect(spy).toHaveBeenCalledWith(jasmine.any(Number))
To expect an object with given key/value properties, use `jasmine.objectContaining(...
How to fix HTML elements being cut off when printing
When you print (or print preview) and elements are cut off (e.g. after 1st page, or "randomly") you should check your CSS rules for these:
-
Is there an element with "
display: inline-block" that surrounds your content? Make sure it has "display: block" for printing.
This primarily affects Firefox and Internet Explorer. Chrome seems to be able to handleinline-blockelements in most cases. -
Does the element itself, or a container, define "
overflow: hidden"? Use "overflow: auto" (or maybe "overflow: visible") instead. -
Is th...
Jasmine: Mocking API requests in an Angular service spec
Situation: You want to write a spec for a function inside an Angular service. This function at some point makes an API request and acts upon response. Notably, your Angular app employs uiRouter, although it is not used nor actually required for this test.
Working test setup
# Capitalized expressions are intended to be replaced with YOUR values
describe 'SERVICE', ->
beforeEach ->
module 'MODULE'
module ($urlRouterProvider) ->
# Prevent uiRouter's initialization, i.e. do not sync the current URL
# with its r...
Limitations you should be aware of when Internet Explorer 9 parses CSS files
Internet Explorer until version 9 has some limitations when parsing CSS files
Summarized, these are:
- Up to 31 CSS files or
<style>tags per page. - Up to 4095 selectors per CSS file.
- Up to 3 nested @import rules
To test the selector limit for a specific browser, check this CSS selector limitation test website.
When you run into this issue, the following links might be helpful to fix the problem. The Idea is to split up the css ...