Negative Index in Coffee-Script

Coffee Script borrowed quite a lot syntax patterns from both Ruby and Python, especially from Ruby.
So people, like me, usually tends to write coffee-script in ruby way.

In ruby, we can retrieve the element in an array in reversed order by using a negative index, which means array[-1] returns the last element in the array. This grammar sugar is really convenient and powerful, so we can omit the code like this array[array.length - 1].

But for some reason, coffee-script doesn’t inherit this syntax. To me, it is weird. But after analyze this problem in detail, I found the reason.
Coffee script announce it has a golden rule: “coffee-script is just javascript”. So all the coffee script must be able to compiled into javascript.

Let’s try to analyze how the coffee script is compiled into javascript:

Coffee Script
1
2
3
array = [1..10]
second = array[1]
last = array[-1] // Psudocode

Obviously, the previous code should be compiled as following:

JavaScript
1
2
3
4
var array, last, second;
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
second = array[1];
last = array[array.length - 1];

The negative index should be processed specially, so we should check the index is negative or not while compiling. This translation seems easy but actually not, since we can and usually use variable as the index.

Variable as index
1
2
3
4
5
array = [1..10]
index = 1
second = array[index]
index = -index
last = array[index]

In the previous code, because we use the variable as index, which cannot be verified in compile-time, which means we need to compile the array reference code as following:

Compile Result
1
2
3
4
5
6
var array, index, last, second;
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
index = 1;
second = index >=0 ? array[index] : array[array.length + index];
index = -index;
last = index >=0 ? array[index] : array[array.length + index];

So every time we reference the array, we need to check whether the index is negative or not. This approach absolutely hurts the performance a lot, which in basically unacceptable.
So that’s why coffee-script doesn’t support the negative index.

Eigenclass in ruby

To me, “Eigenclass” is a weird name. Here is the definition of “Eigenclass” from wikipedia:

A hidden class associated with each specific instance of another class.

“Eigen” is a Dutch word, which means “own” or “one’s own”. So “Eigenclass” means the class that class owned by the instance itself.

To open the eigenclass of the object, Ruby provide the following way:

Open Eigenclass
1
2
3
4
5
6
7
foo = Foo.new
class << foo
# do something with the eigenclass of foo
end

Since the in most cases, the purpose that we open a eigenclass is to define singleton methods on specific object. So Ruby provide an easy way to define the singleton method on specific instance:

Shorten saying
1
2
3
4
5
6
7
foo = Foo.new
def foo.some_method
# do something
end

Since “static method” or “class method” is actually the singleton method of a specific class. So this statement is usually used to declare the “class method”.

Besides this simpler statment, we also can open the eigenclass of the class to achieve the same result.
We can write this:

Open eigenclass of the class
1
2
3
4
5
6
7
8
9
10
11
class Foo
class << self
# define class methods
end
# define instance methods
end

Since we’re in the class block, so the “self” indicates the Foo class instance. So we can use class << self; end to open the eigenclass of the class.

How to solve key_read failed error in git push

I assigned a dedicated ssh key pair for github repos.
And I have associated the key pair with github correctly in ~/.ssh/config.
But each time when I try to access github repos via ssh, both read(such pull or fetch) or write(such as push), I will get a strange error:

key_read: uudecode [some SSH key code]
ssh-rsa [SSH key code]
failed

I tried a lot to fix the problem, and finally I solved the problem by delete the file ~/.ssh/known_hosts
I assume the problem might be caused that there is some invalid association cached in the file. So maybe you can solve the problem by removing the related entries instead of delete the whole file.

Space Pitfall in coffee-script

Coffee Script had fixed quite a lot of pitfalls in Javascript. But on another hand it also introduced some other pitfalls, the most common one is the space.

Space in function declaration

Read the following code:

Show Message:Coffee
1
2
3
4
show = message ->
console.log message
show "space pitfall"

This is a quite simple script, but it failed to run. And if you might also feel confused about the error message: “message is not defined”

What happened to the code? We indeed had declared the message as argument of function show. To reveal the answer, we should analyze the compiled javascript.
Here is the compiled code:

Show Message:JS
1
2
3
4
5
6
7
8
// Generated by CoffeeScript 1.3.1
var show;
show = message(function() {
return console.log(message);
});
showe("space pitfall");

Look the fun declaration, you will see it is not a function declaration as we want but a function call.
The reason is that we omitted the parentheses around the argument and we add a new space between message and ->. So the coffee-script compiler interpret message as a function call with a function as parameter.

Soltuion
To fix this problem, we can remove the space between message and -> to enforce coffee-script compiler interpret them as a whole.

Show Message:Fix
1
2
3
4
show = message->
console.log message
show "space pitfall"

Best Practise
To avoid this pitfall, my suggestion is never omit the parentheses around the arguments, even there is only one argument.
And also including the function call, even coffee-script allow to omit the parentheses. Since you won’t able to chain the method call if you omit the parentheses.
So never omit parentheses, unless you are very certain that there is no any ambiguity and you won’t use method chain.

The space in array index

Since coffee script doesn’t support the negative index. So we should use following code as negative index:

Last Hero:Coffee
1
2
3
heros = ["Egeal Eye", "XMen", "American Captain", "IronMan"]
lastHero = heros[heros -1]
console.log lastHero

This piece of code is also failed to run, and the error message is “property of object is not a function”.
Quite wield right?
Let’s see what is behind the scene, here is the compiled code:

Last Hero:JS
1
2
3
4
5
6
7
8
// Generated by CoffeeScript 1.3.1
var heros, lastHero;
heros = ["Egeal Eyr", "XMen", "American Captain", "IronMan"];
lastHero = heros[heros.length(-1)];
console.log(lastHero);

Same problem, heros.length -1 is interpreted as heros.length(-1) instead of heros.length -1.
To fix this problem, we should write the code in following way:

Last Hero:Fix1
1
2
3
heros = ["Egeal Eye", "XMen", "American Captain", "IronMan"]
lastHero = heros[heros - 1]
console.log lastHero

Or

Last Hero:Fix2
1
2
3
heros = ["Egeal Eye", "XMen", "American Captain", "IronMan"]
lastHero = heros[heros-1]
console.log lastHero

Both solution is try to enforce the compiler divid the component in correct way.

And unfortunately, there is no way to avoid this problem, the only thing you can do is always be aware the spaces in expression.

How to print multiple line string on bash

To display some pre-formatted text onto screen, we need the following 2 capabilities:

Construct Multiple Text

There are 2 ways to construct multiple line strings:

  • String literal

    String Literal
    1
    2
    3
    4
    5
    text = "
    First Line
    Second Line
    Third Line
    "
  • Use cat

    cat
    1
    2
    3
    4
    5
    6
    text = $(cat << EOF
    First Line
    Second Line
    Third Line
    EOF
    )

For some reason, echo command will eat all the line break in the text, so we should use printf instead of echo.
And printf supports back-slash-escape, so we can use \n to print a new-line on screen.

Dynamic Singleton Methods in Ruby

Today, I pair with Ma Wei to refactor a piece of pre-existed code. We try to eliminate some “static methods” (in fact, there is no real static method in ruby, I use this term to describe the methods that only depends on its parameters other than any instance variables).

The code is like this:

Recruiter.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Recruiter
def approve! candidates
Candidate.transaction do
candidates.each do |candidate|
candidate.status.approve!
end
end
end
def reject! candidates
Candidate.transaction do
candidates.each do |candidate|
candidate.status.reject!
end
end
end
def revoke! candidates
Candidate.transaction do
candidates.each do |candidate|
candidate.status.revoke!
end
end
end
# ...
# Some other methods similar
end

As you can see the class Recruiter is used as a host for the methods that manipulate the array of candidates, which is a strong bad smell . So we decide to move these methods to their context class.

In Java or C#, the solution to this smell is quite obvious, which could be announced as “Standard Answers”:

  1. Mark all methods static.
  2. Create a new class named CandiateCollection.
  3. Change the type of candidates to CandidateCollection.
  4. Mark all methods non-static, and move it to CandidateCollection class.
    If you use Resharper or IntelliJ enterprise version, then the tool can even do this for you.

But in ruby world, or even in dynamic language world, we don’t like to create so many classes, especially these “strong-typed collection”. I wish I could inject these domain related methods to the array instance when necessary, which is known as “singleton methods” in ruby.
To achieve this, I might need the code like this:

Singleton Methods
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def wrap_array array
def array.approve!
# ...
end
def array.reject!
# ...
end
# ...
# Some other methods similar
array
end

With the help of this wrap_array method, we can dynamic inject the method into the array like this:

call wrap_array
1
wrap_array(Candidate.scoped_by_id(candidate_ids)).approve!

This is cool, but still not cool enough. We still have problems:

  1. All the business logic is included in the wrap method. It is hard to maintain.
  2. Where should we declare this wrap method? In class Array or another “static class”?

The answer to the 1st question is easy, our solution is encapsulate these logics into a module:

Module CandidateCollection
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
module CandidateCollection
def approve!
# ...
end
def reject!
# ...
end
def revoke!
# ...
end
# ...
# Some other methods similar
end
end

By encapsulate the logic into a module, then we can extract it into a single file, so the logic could be organized in the way as we want.
Now we need to solve the second problem and reuse the module we just created.

To achieve this, we wrote the following code:

Array.to_candidate_collection
1
2
3
4
5
6
7
8
class Array
def to_candidate_collection
class << self
include CandidateCollection
end
self
end
end

In the code, we re-opened the class Array, and define a new method called to_candidate_collection, which is used to inject domain methods into a generic array.
So we can have the following code:

Call to_candidate_collection
1
Candidate.scoped_by_id(candidate_ids).to_candidate_collection.approve!

Now our refactoring is basically completed.

But soon, we realize that is pattern is really powerful and should be able to be reused easily. So we decide to move on.
We want to_candiate_collection be more generic, so we can dynamically inject any module, not just CandidateCollection.
So we wrote the following code:

dynamic_inject
1
2
3
4
5
6
7
8
class Array
def dynamic_inject module
class << self
include module
end
self
end
end

So we can have the code like this:

call dynamic_inject
1
Candidate.scoped_by_id(candidate_ids).dynamic_inject(CandidateCollection).approve!

The code looks cool, but failed to run.
The reason is that we opened the meta class of the instance, which means we enter another level of context, so the parameter module is no longer visible.
To solve this problem, we need to flatten the context by using closure. So we modified the code as following:

dynamic_inject version 2
1
2
3
4
5
6
7
8
9
class Array
def dynamic_inject module
metaclass = class << self; self; end
metaclass.class_eval do
include module
end
self
end
end

The code metaclass = class << self; self; end is very tricky, we use this statement to get the meta class of the array instance.
Then we call class_eval on meta class, which then mixed-in the module we want.

Now the code is looked nice. We can dynamically inject any module into “Array” instance.
Wait a minute, why only “Array”? We’d like to have this capability on any object!
Ok, that’s easy, let’s move the method to Kernel module, which is mixed-in by Object class.

dynamic_inject version 3
1
2
3
4
5
6
7
8
9
module Kernel
def dynamic_inject module
metaclass = class << self; self; end
metaclass.class_eval do
include module
end
self
end
end

Now we can say the code looks beautiful.

NOTICE:
Have you noticed that we have a self expression at the end of the dynamic_inject method as return value.
This statement is quite important!
Since we will get “undefined method error” when calling Candidate.scoped_by_id(candidate_ids).dynamic_inject(CandidateCollection).approve! if we missed this statement.
We spent almost 1 hour to figure out this stupid mistake. It is really a stupid but expensive mistake!


Instead of these tricky ways, for Ruby 1.9+, it is okay to use extend method to replace the tricky code.
The extend method is the official way to do “dyanamic inject” as described before.

How to launch Mac OS Terminal as Interactive Shell rather than Log-in Shell

As described in previous post, Mac OS launch its terminal as Log-In shell rather than Interactive Shell, which is different to default behavior of Unix and Linux. As a result, Terminal will load “bash_profile” as its profile rather than the normal “bashrc”.

This unique behavior might cause some problem when you try to port CLI tool from Unix or Linux.
Because basically, the ported app infers that the bash_profile should be loaded only once, and only when user just logged in. But in Mac OS, this inference is wrong, which can cause some weird problem.

This default behavior sometimes is annoying, and in fact, this Mac OS Terminal’s “unique” behavior can be configured. And even more, you can use other shell program, such as ksh, rather than the default bash.

Mac user can customize this behavior in Terminal’s Preferences dialog of Terminal app.
Terminal Preferences Dialog

If you choose the command to launch bash, the launched shell will become a interactive shell, which will load .bashrc file rather than .bash_profile file.