View

Aruba: Stubbing binaries

When testing your command line application with Aruba, you might need to stub out other binaries you don't want to be invoked by your test.

Aruba Doubles is a library that was built for this purpose. It is not actively maintained, but works with the little fix below.

Installation

Install the gem as instructed by its README, then put this Before block somewhere into features/support:

```
Before do
ArubaDoubles::Double.setup
prepend_environmen…

Repeats

Organize large I18n dictionary files in Rails 3+

If you're suffering from a huge de.yml or similiar file, cry no more. Rails lets you freely organize your dictionary files in config/locales.

My organization works like this:

  • config/locales/rails.de.yml modified Rails boilerplate
  • config/locales/faker.de.yml modified Faker boilerplate
  • config/locales/models.de.yml model names, attribute names, assignable_value labels
  • `config/locales/views.de.y…
External content

Subclassing module

Yesterday I stumbled across a talk in which the guy mentioned module sub-classing. I was curious what you can do with it and found his blog post with a cool example. It allows you to inject some state into the module you are including elsewhere. Check it out!

```
class AttributeAccessor < Module
def initialize(name)
@name = name
end

def included(model)
super
define_accessors
end

private

def define_accessors
ivar = "@#{@name}"
define_writer(ivar)
define_reader(ivar)
end

def define_writer(ivar)

Repeats

Protected and Private Methods in Ruby

In Ruby, the meaning of protected and private is different from other languages like Java. (They don't hide methods from inheriting classes.)

private

Private methods can only be called with implicit receiver. As soon as you specify a receiver, let it only be self, your call will be rejected.

class A
 
  def public_method
    private_method
  end
  
  def other_public_method
    self.private_method
  end
  
  private
  
  def private_method
    "I'm private"
  end
 ...
Repeats

Rails: Talking to the database without instantiating ActiveRecord objects

Instantiating ActiveRecord objects comes expensive. To speed up things, you can choose a more direct way to talk to your database: the ActiveRecord::ConnectionAdapters::DatabaseStatements module.

Using the module and its methods is not suggested in the usual in-app workflow, as validations, callbacks, custom getters/setters etc. are ignored. However, for database-centered stuff like migrations, these fill the gap between writing pure SQL and full…

AngularJS: How to remove a watch

Sometimes you want Angular to watch an object only until a certain state is reached (e.g. an object appears in the scope).

Angular's $watch returns a method that you can call to remove that watch. For example:

unwatch = $scope.$watch 'user', (user) ->
  if user?
    ... # do something
    unwatch()

That's it.

Hide a Rake task from the `rake -T` list

A Rake task appears in rake -T if it has a description:

desc 'Compile assets'
task :compile do
  ...
end

To not list it, simply omit the description:

task :compile do
  ...
end

You can also hide a Rake task that has been defined by someone else (like a gem) by removing the description:

Rake::Task['compile'].clear_comments

Or you can whitelist which tasks should be listed:

```
visible_tasks = %w(compile build package)
Rake::Task.tasks.each do |task|
visible_tasks.include?(task.name) or task.clear_comments
en…

Ruby: Writing specs for (partially) memoized code

When you're writing specs for ActiveRecord models that use memoization, a simple #reload will not do:

it 'updates on changes' do
  subject.seat_counts = [5]
  subject.seat_total.should == 5
  # seat_total is either memoized itself, or using some
  # private memoized method
  
  subject.seat_counts = [5, 1]
  subject.seat_total.reload.should == 6 # => Still 5
end

You might be tempted to manually unmemoize any memoized internal method to get #seat_total to update, but that has two disadvant…

Angular with haml: Dynamic html classes

A haml angular 1 template with

.thing(class="is-{{:: item.type }}")

will be compiled (by haml) to

<div class="is-{{:: item.type thing }}"></div>

which is not what you want! It will also crash in angular (unless thing is a valid variable in your angular directive) with Error: [$parse:syntax] Syntax Error: Token 'thing' is an unexpected token at column 11 of the expression [item.type thing]

Solution 1: Use ng-class instead of class

.thing(ng-class='"is-{{ item.type }}"')

**Solution 2: Don't let haml b…

External content

Understanding AngularJS service types

Angular comes with different types of services. Each one with its own use cases.

All of these services are singletons. You probably want to use Factory all the time.

Provider

  • is the parent of all other services (except constant)
  • can be configured using `app.config(function(Provider) { ...})
  • a little complex

Factory

  • simpler than Provider, but without configuration
  • definition: `app.factory('name', someFunction)
  • someFunction is called when the name service is instantiated and should return an object

Se…

Repeats

Nested ActiveRecord transaction pitfalls

When working with custom transactions you may encounter unexpected behaviour if you try to roll back your changes.

tl;dr

Not all databases support nested transactions. Therefore, Rails will sometimes silently ignore a nested transaction and simply reuse the other transaction. However, a ActiveRecord::Rollback within the nested transaction will be caught by the block of the nested transaction, but will be ignored by the outer transaction, and not cause a roll back!
To avoid this unexpected behaviour, you have to explicitly tell rai…

Repeats

How to emulate simple classes in JavaScript

Since ES6 classes still have limited browser support, one workaround to ensure encapsulation is the revealing module pattern.

Example

Here is an example for a Ruby class that we want to translate into Javascript using the module pattern.

It's a simple class with one private function:

```
class Dog

def initiali…

Repeats

How to create columns like "bigint" or "longtext" in Rails migrations, and what :limit means for column migrations

Rails understands a :limit options when you create columns in a migration. Its meaning depends on the column type, and sometimes the supplied value.

The documentation states that :limit sets the column length to the number of characters for string and text columns, and to the number of bytes for binary and integer columns.

Using it

This is nice since you may want a bigint column to store really long numbers in it. You can just create it by …

Repeats

Copy to clipboard without flash (clipboard.js)

We used zeroclipboard.js in some of our projects but now we switched to clipboard.js because it does not rely on flash. Flash support of the major browsers ends.

Some more advantages of clipboard.js:

  • it consists only of a single javascript file, so it does not trigger additional requests with rails
  • it automagically provides user feedback by selecting the text it has copied
  • it provides callbacks for success and error which make it easier to add custom behaviour after copying to the clipboard
  • i…

Add monitoring for Sidekiq

In order to have monitoring for Sidekiq (like queue sizes, last run of Sidekiq) your application should have a monitoring route which returns a json looking like this:

```
{
"sidekiq": {
"totals": {
"failed": 343938,
"processed": 117649167
},
"recent_history": {
"failed": {
"2016-11-06": 1,
"2016-11-07": 46,
"2016-11-08": 0,
"2016-11-09": 0,
"2016-11-10": 0
},
"processed": {
"2016-11-06": 230653,
"2016-11-07": 230701,
"2016-11-08": 23…

External content

mceachen/closure_tree: Easily and efficiently make your ActiveRecord models support hierarchies

Closure_tree lets your ActiveRecord models act as nodes in a tree data structure.

This promises a few improvements over the battle-tested ancestry gem, such as:

  • Better performance (an issue because ancestry does full table scans with Regexps on the ancestry column)
  • Pre-ordered trees (painful to do with ancestry)
  • Holds a mutex during tree manipulations (an issue with ancestry, where concurrent updates can cause deadlocks and corrupt data).

It has…

External contentRepeats

The Easiest Way to Parse URLs with JavaScript

A very clever hack to parse a structured URL object is to create a <a> element and set its href to the URL you want to parse.

You can then query the <a> element for its components like schema, hostname, port, pathname, query, hash:

var parser = document.createElement('a');
parser.href = 'http://heise.de/bar';
parser.hostname; // => 'heise.de'
parser.pathname; // => '/bar'

One advantage vs. calling new URL(...) is that it works with incomplete URLs. So if al…

How to inspect really large directories

When a directory has more than a few thousand entries, ls will start taking really long to list its content. Reason for this is that ls by default a) sorts the file names and b) prints them in columns. For both, it needs to know (thus load into memory) the whole list of files before it can start printing anything.

By disabling sorting and columns, you get a lean, superfast ls that prints "live" as it reads:

$> ls -f -1
file1
file2
...
file9999
file10000
file10001
...
View
3267 cards