Ruby: Counting occurrences of an item in an array / enumerable

Enumerable#count can do three things.

  • With no argument provided, it returns the number of items.
  • With an argument, it returns the number of items matching the given value.
  • With a block, it counts the number of elements yielding a truthy value.
ary = [1, 2, 4, 2]
ary.count #=> 4
ary.count(2) #=> 2
ary.count { |x| x % 2 == 0 } #=> 3

Ruby: Flatten arrays by only one level

Array#flatten by default flattens an array recursively. To only flatten the array for e.g. one level, it takes an optional argument.

# Flattens the array recursively
>> [1, [2, [3]]].flatten
=> [1, 2, 3]

# Flattens the array the given number of times
>> [1, [2, [3]]].flatten(1)
=> [1, 2, [3]]

Fix error UDPSocket.open: wrong number of arguments (0 for 1)

I got the following error after updating the selenium-webdriver gem:

wrong number of arguments (0 for 1) (ArgumentError)
/home/pointoo-dev/.rvm/gems/ruby-1.8.7-p374/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver/common/platform.rb:183:in `open'
/home/pointoo-dev/.rvm/gems/ruby-1.8.7-p374/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver/common/platform.rb:183:in `ip'
/home/pointoo-dev/.rvm/gems/ruby-1.8.7-p374/gems/selenium-webdriver-2.35.1/lib/selenium/webdriver/common/platform.rb:196:in `interfaces'

It was caused...

grosser/rspec-instafail

Gem to show failing specs instantly.
Unlike the --fail-fast option it doesn't abort abort on the first failure, but keeps running other examples after print out the failure.

I haven't tried it with parallel_tests.

Rails: Running specific migrations

When running migrations with rake db:migrate, there's the STEP and VERSION parameters that you can pass to nearly all commands.

# Migrate
rake db:migrate
rake db:migrate STEP=2
rake db:migrate VERSION=20080906120000

# Redo
rake db:migrate:redo
rake db:migrate:redo STEP=2
rake db:migrate:redo VERSION=20080906120000

# Rollback (starting from latest migration)
rake db:rollback
rake db:rollback STEP=2

# Run the `down` migration path of a certain migration file
rake db:migrate:down VERSION=20080906120000

Did you know 'tig status' ?

It's like a GUI for the famous git add [-p].

Select files with the up/down-keys and hit

  • u for staging/unstaging the whole file
  • Enter for showing the diff of a file
    • j and k to navigate in the diff
    • u again to stage/unstage chunks
    • 1 to stage/unstage only lines
    • \ to split large chunks
  • F5 to refresh the view

How to detect touch-capable browsers

The easiest way to detect touch-capable browsers is to check for the presence of touch events. It is no 100% solution, but has by far the best cost-benefit ratio. (Know that this does not detect touch devices, but browsers.)

Javascript

var isTouchDevice = 'ontouchstart' in window

Coffeescript

isTouchDevice = 'ontouchstart' of window

On the difference between the Javascript and the Coffeescript version, see [Beware: Coffeescript "in" is not the Javascript "in"](https://makandracards.com/makandra/31073-beware-c...

Beware: Coffeescript "in" is not the Javascript "in"

The Javascript in operator does what Hash#has_key? does in Ruby: Return whether an object has a property.
However, Coffeescript has its own in operator that checks for array inclusion. To check whether an object has a property, use of:

Javascript

'name' in {name: 'Horst'} # => true

Coffeescript

# wrong
'name' in {name: 'Horst'} # => false

# correct
'name' of {name: 'Horst'} # => true
1 in [1,2,3] # => true

True story.

Block formatting contexts

TL;DR Block formatting contexts establish an isolating container. float
and clear only apply to elements within such a container.

About

Block formatting contexts (BFCs) are important for the positioning and clearing
of floats. The rules for positioning and clearing of floats apply only to
things within the same block formatting context.

Floats do not affect the layout of things in other block formatting contexts,
and clear only clears past floats in the same block formatting context.

How to create a new block form...

LibreOffice Writer: Prevent a table row from being split across pages

  • Right-click on the table
  • Select Table...
  • Select Text flow
  • Uncheck Allow row to break across pages and columns

Ruby: Find a hash key given it's value

To find a hash key by it's value, i.e. reverse lookup, one can use Hash#key. It's available in Ruby 1.9+.

Hash#key(value) → key
# => Returns the key of the first occurrence of a given value.
     If the value is not found, returns nil.

hash = { "a" => 100, "b" => 200, "c" => 300, "d" => 300 }
hash.key(200)   #=> "b"
hash.key(300)   #=> "c"
hash.key(999)   #=> nil

Git: How to get a useful diff when renaming files

tldr; Use git diff -M or git diff --find-renames when you've moved a few files around.

Usage

$ git diff --help
  Options:
    -M[<n>], --find-renames[=<n>]
      Detect renames. If n is specified, it is a threshold on the similarity index
       (i.e. amount of addition/deletions compared to the file’s size). For example,
       -M90% means Git should consider a delete/add pair to be a rename if more than
       90% of the file hasn’t changed. Without a % sign, the number is to be read as
       a fraction, with a decimal point...

Angular + ui-router: Make links work in a new tab

If your angular app is not served on /, but on a different url (say /admin), links generated with ui-router will not work when you open them in a new tab.

Fix this by adding this tag in your <head>:

<base href='/admin#/'>

Helper method:

def base_tag
  tag(:base, href: request.path_info + "#/")
end

hanklords/flickraw

Flickraw is a library to access flickr api in a simple way. It maps exactly the methods described in the official api documentation. It also tries to present the data returned in a simple and intuitive way. The methods are fetched from flickr when loading the library by using introspection capabilities. So it is always up-to-date with regards to new methods added by flickr.

Preview Github-flavored Markdown from the bash with ianks/octodown

Preview what your markdown would look like on Github. Helpful e.g. when writing or extending a Readme for your gem or projects.

Installation

sudo apt-get install cmake libicu-dev # required for building native extensions
gem install octodown

Know that this will install at least 12 other gems. However, the beautiful output should be worth it.

Usage

octodown README.md

octodown markdown preview

greckout - a bash script to grep and checkout your git branches

greckout query

This will list all branches matching your query as input options for git checkout

  greckout ar
  
  1) ar/cache-api-keys-1098
  2) ar/add-categories-object-to-tv-show-1382
  3) ...

How to load an SQL dump from a migration

If you want to load an SQL dump from an ActiveRecord migration, you might find this to be harder than you thought. While you can call ActiveRecord::Base.connection.execute(sql) to execute arbitrary SQL commands, the MySQL connection is configured to only accept a single statement per query. If you try to feed it multiple statements, it will die with You have an error in your SQL syntax.

You can work around this by opening a second MySQL connection that does accept multiple statements per call.

Below is an example for a migration that l...

Why Learning to Code is So Damn Hard

In this post, I'll walk you through the four phases of the typical journey into coding and what you'll need to do to survive each of them.

Debugging "INTERNAL ERROR!!! wrong argument type StringIO (expected File)"

If you're getting this strange error message when setting debugging breakpoints, probably HAML is the culprit.

Cause

As far as I could find out, the error is the result of setting a breakpoint (debugger) in a helper method that's called from a haml partial.

Suggestions

Try putting the breakpoint into the HAML view.

Cucumber factory 1.10.0 released

I've pushed an update to Cucumber factory that simplifies working with FactoryGirl factories.

Say you define a factory with the class: option:

factory :admin, class: User
  email
  admin true
end

In the past, you had to write

Given there is a user (admin)

Now you can simply write

Given there is an admin

The class is inferred from the factory.

RSpec: Only stub a method when a particular argument is passed

To only stub a method call if a given argument is used, but use the default implementation for other arguments:

object.should_receive(:some_method).and_call_original
object.should_receive(:some_method).with('my argument').and_return('other value')

Requires rspec-mocks 2.13+.

Capybara - The missing API

The Capybara API is somewhat hard for parse for a list of methods you can call on a Capybara node. Below you can find such a list. It's all copied from the Capybara docs, so all credit goes to the Capybara committers.

When you talk to Capybara from a Cucumber step definition, you always have page as the document root node, or whatever you scoped to by saying within(selector) { ... }. You can select child notes by calling page.find(selector) or page.all(selector). You can call the same ...

Ubtuntu: "FATAL: Could not load /lib/modules/...-generic/modules.dep: No such file or directory"

If you get this error (probably because you want to load some modules):

# modprobe xt_comment
FATAL: Could not load /lib/modules/3.2.0-40-generic/modules.dep: No such file or directory

The reason could be that apt-get autoremove already removed /lib/modules/.../modules.dep even if you still using this kernel version:

# uname -r
3.2.0-40-generic
# ls -l /lib/modules/
total 24
drwxr-xr-x 4 root root 4096 Oct 22 17:05 3.2.0-68-generic
drwxr-xr-x 4 root root 4096 Jan  7 16:38 3.2.0-69-generic
drwxr-...