View

Custom Ruby method #count_by

I frequently find myself needing a combination of group_by, count and sort for quick statistics. Here's a method on Enumerable that combines the three:

module Enumerable
  def count_by(&block)
    group_by(&block)
      .map{ |key, items| [key, items.count] }
      .sort_by(&:last)
  end
end

Usage

Listing the number of new users per day: User.all.count_by { |user| user.created_at.to_date }

More tools

If you need further options, here's a "toolbox" of chainable method invocations:

```
list
.group_by{ |item| <D…

Auto-destruct in 55 days

Updated: How to set up database_cleaner for Rails with Cucumber and RSpec

RSpec

# spec/support/database_cleaner.rb

RSpec.configure do |config|
  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:deletion)
  end

  config.around do |example|
    DatabaseCleaner.start
    example.run
    DatabaseCleaner.clean
  end
end
# spec/spec_helper.rb

RSpec.configure do |config|
  config.use_transactional_fixtures = false
end 

Don't use before hooks here otherwise around hooks are not within the transaction and your database is therefore not cleaned pro…

External contentRepeats

Helper methods - RSpec Core

You can define methods in any example group using Ruby's def keyword or define_method method. These helper methods are exposed to examples in the group in which they are defined and groups nested within that group, but not parent or sibling groups.

Repeats

Migrating legacy data into new application

There are many approaches out there how you can import data from a legacy application to a new application. Here is an approach which opens two database connections and uses active record for the legacy system, too:

1. Add you database information to you config/database.yml.

data_migration:
  database: your_application_data_migration

2. Create a separate application record for the data migration, e.g. in app/data_migration/migration_record.rb. You will need to create an app/data_migration.rb class first.

```
class DataMig…

Repeats

An auto-mapper for ARIA labels and BEM classes in Cucumber selectors

Spreewald comes with a selector_for helper that matches an English term like the user's profile into a CSS selector. This is useful for steps that refer to a particular section of the page, like the following:

Then I should see "Bruce" within the user's profile
                                 ^^^^^^^^^^^^^^^^^^

If you're too lazy to manually translate English to a CSS selector by adding a line to features/env/selectors.rb, we already have an [auto-mapper to translate English into …

Repeats

Git: Improve your commits by reviewing changes one-by-one

Git commits should be very deliberate, and only contain changes that you really want to be in there. In order to reduce the chance to accidentally commit something you didn't intend, review your changes before committing.

My preferred way of doing this is (only using git)

git add -N . # Add all paths, but not their contents
git add -p

Git will now show you all your changes in small chunks and ask you in an interactive mode whether you really want to add them.

The most helpful commands are

  • y: yes (add the change)
External content

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.

Repeats

Rspec: around(:all) and around(:each) hook execution order

Summary

  • around(:suite) does not exist.
  • around(:all) runs after before(:all) and before after(:all).
  • around(:each) runs before before(:each) and after after(:each).

As this is not 100% obvious (and not yet documented) it is written down in this card. In RSpec 3 :each has the alias :example and :all the alias :context.

Example

```
RSpec.configure do |config|
config.before(:suite) { puts 'BEFORE :suite' }
config.after(:suite) { puts 'AFTER :suite' }
end

describe 'order of hook execution' do
around(:a…

External contentRepeats

Using pure Sass functions to make reusable logic more useful - Advanced

Functions and mixins are very similar in nature. Because they can both accept variables, you might end up creating a mixin when what you really need is a function.

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…

Repeats

Why two Ruby Time objects are not equal, although they appear to be

So you are comparing two Time objects in an RSpec example, and they are not equal, although they look equal:

expected: Tue May 01 21:59:59 UTC 2007,
     got: Tue May 01 21:59:59 UTC 2007 (using ==)

The reason for this is that Time actually tracks fractions of a second, although #to_s doesn't say so and even though you probably only care about seconds. This means that two consecutive calls of Time.now probably return two inequal values.

If you only care about second precision you can compare two Times by calling #to_i

JavaScript: How to query the state of a native 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
External contentRepeats

CSS Support Guide for Email Clients

CSS support in major e-mail clients is horrible.

This will give you an overview what you will not be able to use across all clients.

Repeats

How to use a local gem in your Gemfile

You can use local copies of gems in your Gemfile like this:

gem 'spreewald', :path => '~/gems/spreewald'

As soon as you have bundled your project with the local copy of the gem, all code changes in the copy will be available on your project. So you can for example set a debugger (or add console output) in the gem and use it from your project.
If you checked out the gem using git (or any other versioning tool), you can easily reset your changes afterwards or make a pull request for the gem if you improved it.

Repeats

Rails: When defining scopes with class methods, don't use `self`

Sometimes it is useful to define a named scope by implementing a static method with the scope's name on the scoped class. For instance, when a method should decide which existing scope should be the next link in the scope chain. Take this class for example:

class Meal < ActiveRecord::Base

  named_scope :for_date, lambda { |date| :conditions => { :date => date }}
  named_scope :with_meat, :conditions => { :meat => true }
  named_scope :without_meat, :conditions => { :meat => false }

  def self.suitable_for(user)
   ...
View
3345 cards