Git error: "badTimezone: invalid author/committer line - bad time zone"
You might get the above error message when cloning certain git repositories (for example the rails repository). It indicates that there is a malformed timestamp in some commit, and your git installation is configured to validate it.
As a workaround, you can disable the validation using
git config --global fetch.fsckobjects false
This settings seems to be the default for most git installations anyways.
makandra/gemika: Helpers for testing Ruby gems
We have released a new library Gemika to help test a gem against multiple versions of Ruby, gem dependencies and database types.
Here's what Gemika can give your test's development setup (all features are opt-in):
- Test one codebase against multiple sets of gem dependency sets (e.g. Rails 4.2, Rails 5.0).
- Test one codebase against multiple Ruby versions (e.g. Ruby 2.1.8, Ruby 2.3.1).
- Test one codebase against multiple database types (currently MySQL or PostgreSQL).
- Compute a matrix of all possib...
VCR fails if the same request is triggered multiple times
Same requests are recorded only once in vcr. Replaying a test fails, if you trigger the same request multiple times. The error message is somehow confusing, as your cassette contains the request:
An HTTP request has been made that VCR does not know how to handle
If you want to allow to match a request multiple times, you need to configure this explicit with allow_playback_repeats: true. Some exa...
Migrations are versioned in Rails 5 | BigBinary Blog
Rails 5 migration classes look like this now:
class CreateUsers < ActiveRecord::Migration[5.0]
Mind the [5.0] at the end.
They do this to evolve the ActiveRecord::Migration API without breaking your historical migrations in db/migrate.
Measuring sql query time of a piece of code using ActiveSupport::Notifications
ActiveSupport::Notifications provides an instrumentation API for Ruby. It is used throughout rails to publish instrumentation events that include information about each part of a request/response cycle.
Have a look at your application log file - yes, those are those events. The cool thing is that you can subscribe to those events.
There is also a convenience method that allows you to subscribe to those events only for the time of executing a block of code. Thus you can capture all sql queries that are triggered when executing your block....
How to use Haml in your helpers
You know those helper methods that just render some HTML but look weird because of content_tags all over the place? You could also use Haml instead.
Example
Consider the following helper.
def greeting
message = ''.html_safe
message << 'Welcome to '
message << content_tag(:span, Rails.env, class: 'greeting--location')
content_tag :div, message, class: 'greeting'
end
That looks clumsy and is hard to read.
Wouldn't it be nicer to say something like this?
def greeting
render_haml <<-HAML
...
Minidusen: Low-tech record filtering with LIKE queries
We have a new gem Minidusen which extracts Dusen's query parsing and LIKE query functionality.
Minidusen can no longer index text in MySQL FULLTEXT columns, which was hardly used and didn't always help performance due to the cost of reindexing.
Minidusen is currently compatible with MySQL, PostgreSQL, Rails 3.2, Rails 4.2 and Rails 5.0.
Basic Usage
Our example will be a simple address book:
class Contact < ActiveRecord::Base
validates_presence_of :name, :street, :city, :e...
We are no longer maintaining Dusen
If you were using Dusen for its query parsing and LIKE queries, we recommend to migrate to Minidusen, which extracts those parts from Dusen. Minidusen is compatible with MySQL, PostgreSQL and Rails 3.2, 4.2 and 5.0.
If you are looking for a full text indexing solution, we recommend to use PostgreSQL with pg_search.
Capistrano: exclude custom bundle groups for production deploy
Capistrano is by default configured to exclude the gems of the groups development and test when deploying to the stages production and staging. Whenever you create custom groups in your Gemfile, make sure to exclude these, if they should not be deployed to the servers. The gems of these groups might not be loaded by rails, however, the deployment process will take longer as the gems will be downloaded and installed to the server.
e.g. to exclude the groups cucumber and deploy, add the following to `config/deploy/production.rb...
Using Spring and parallel_tests in your Rails application
You want Spring for super-fast binstubs like bin/rails or bin/rspec which avoid Rails boot time.
You want parallel_tests to speed up full test runs of large test suites.
Unfortunately, you do not want parallel_tests to use your Spring binstubs as those parallelized tests will share data and/or loose some information. There are some issues about this on GitHub and there is a suggested [workaround](https:...
An intro to Javascript promises
Promises are the new way™ to express "Do this, and once you're done, do that". In contrast to callbacks, promises are easily chainable. From the readme of Q, an early implementer of the pattern:
The callback approach is called an “inversion of control”. A function that accepts a callback instead of a return value is saying, “Don’t call me, I’ll call you.”. Promises un-invert the inversion, cleanly separating the input arguments from control flow arguments. This simplifies the use and creation of APIs, p...
MySQL: How to dump single tables instead of a complete database
Sometimes you want to test migrations with production or staging data. Dumping single tables makes sense if a complete dump would be to big.
mysqldump -u deploy_user -p application_production table1 table2 table2 > table1_table2_table2.sql.dump
Hint: If a table has to many constraints, a complete dump could be more handy.
Further reading:
- How to load only a subset of a massive MySQL dump
- [How to import production database dump t...
Rails: How to get PostgreSQL version being used
To check the currently running PG version from your Rails application (e.g. Rails console on your production server), simply do this:
ActiveRecord::Base.connection.select_value('SELECT version()')
Case sensitivity in PostgreSQL
PostgreSQL, unlike MySQL, treats strings as case sensitive in all circumstances.
This includes
- comparison with
=andLIKE - collision detection in unique indexes
Usually this is fine, but some strings (like emails and usernames) should typically be treated as case insensitive.
There are a few workarounds available:
- use the citext extension (not recommended)
- use
ILIKEinstead ofLIKE - use Postgres'
lower()function - add an index on
lower(email)
Probably th...
JavaScript: Stopping expensive work in inactive tabs
Is your application doing something expensive every few seconds? Maybe an animated slider that rotates images? Maybe you are updating data over the network every five minutes? It's a good idea to pause this if the your document tab is not even visible to the user. This saves your user's battery and data plan.
You can ask document.visibilityState or document.hidden whether this tab is visibl...
Represent astral Unicode characters in Javascript, HTML or Ruby
Here is a symbol of an eight note: ♪
Its two-byte hex representation is 0x266A.
This card describes how to create a string with this symbol in various languages.
All languages
Since our tool chain (editors, languages, databases, browsers) is UTF-8 aware (or at least doesn't mangle bytes), you can usually get away with just pasting the symbol verbatim:
note = '♪'
This is great for shapes that are easily recognized by your fellow programmers.
It's not...
Building web applications: Beyond the happy path
When building a web application, one is tempted to claim it "done" too early. Make sure you check this list.
Different screen sizes and browsers
Desktops, tablets and mobile devices have all different screen resolutions. Does your design work on each of them?
- Choose which browsers to support. Make sure the page looks OK, is usable and working in these browsers.
- Use @media queries to build a responsive design
- If you do not suppo...
Google Chrome: How to find out your currently installed theme
So you downloaded a theme for Chrome a while ago and don't remember which one it is?
You can go to chrome://settings/appearance (on Chrome 61+) to see the theme's name, and click a link to open it in the Chrome Web Store.
If you are on an older version, or if the above no longer works, you have to check Chrome's Preferences file.
Linux
/home/YOUR_USER_NAME/.config/chromium/Default/Preferences
OSX
/Users/YOUR_USER_NAME/Library/Application Support/Google/Chrome/Default/Preferences
Windows
C:\Users\YOUR_US...
There is no real performance difference between "def" and "define_method"
You can define methods using def or define_method. In the real world, there is no performance difference.
define_method is most often used in metaprogramming, like so:
define_method :"#{attribute_name}_for_realsies?" do
do_things
end
Methods defined via define_method are usually believed to have worse performance than those defined via def.
Hence, developers sometimes prefer using class_eval to define methods using def, like this:
class_eval "def #{attribute_name}_for_realsies?; do_things; end"
You can be...
ActiveRecord subselects - Today I Learned
Apparently you can pash a second scope to a hash-condition and the whole thing will be evaluated as a second SELECT statement with a subselect.
Note that sub-queries are extremely slow in MySQL, but they can make cases easier where performance does not matter so much (e.g. a migration on 50K records).
has_one association may silently drop associated record when it is invalid
This is quite an edge case, and appears like a bug in Rails (4.2.6) to me.
Update: This is now documented on Edgeguides Ruby on Rails:
If you set the :validate option to true, then associated objects will be validated whenever you save this object. By default, this is false: associated objects will not be validated when this object is saved.
Setup
# post.rb
class Post < ActiveRecord::Base
has_one :attachment
end
# attachm...
Download Ruby gems without installing
You can download .gem files using gem fetch:
gem fetch activesupport consul
This will produce files like active-support-5.0.0.gem and consul-0.12.1.gem in your working directory.
Dependencies will not be downloaded.
Linux: Find out which processes are swapped out
Processes in Linux might be put into Swap ("virtual memory") occasionally.
Even parts of a single process might be removed from memory and put into Swap.
In order to find out which processes remain within Swap, run this:
sudo grep VmSwap /proc/*/status | egrep -v "0 kB"
Keep in mind Swap is not evil by definition. Some bytes per process beeing put to Swap will not have that much of performance influence.
If you want the Linux virtual memory manager (which is responsible for the decision if and which processes are moved to Swap) to be...
Tasks, microtasks, queues and schedules - JakeArchibald.com
The way that Javascript schedules timeouts and promise callbacks is more complicated than you think. This can be the reason why callbacks are not executed in the order that they are queued.
Please read this article!
This is an extract of the example in the article which demonstrates the execution order of tasks and microtasks.
console.log('script start');
setTimeout(function() {
console.log('setTimeout');
}, 0);
Promise.resolve().then(function() {
console.log('promise1');
}).then(function() {
console.log('promise2');
})...