As you probably know I’m active Vim user, I’ve been using Vim daily for about 3 years. I’ve started with a vimconfig of my friend @kossnocorp then I tried Vim distribution called “Janus”, but it was complex and I decided to create my own small vimconfig, now it’s about 200 LOC and I’m always trying to keep it as simple as possible. I’ve not written any single Vim plugin in the three years, I have a small one (vim-railsapi, but it’s not really smth serious, one of the reasons is VimL, I think :)

A few days ago

I’ve decided to try Emacs.

Why?

  • EmacsLisp instead of VimL
  • Built-in package manager from version 24
  • Good support for Lisps including Clojure
  • And for other funcitonal languages
  • And of course just for fun

What do I really need?

  • Of course Vi motions
  • Relative numbers
  • Supertab auto completion
  • Buffer explorer
  • Ack for files

Support for langauges it’s not really a problem in editors like Emacs, I think, that is why I’m not counting it here. I started with my own empty .emacs.d First thing I added was evil-mode, because my fingers can’t live w/o vi-motions. Evil-mode works really perfect without any problems and helped me to reduce amount of Ctrl clicks. Next step is relative numbers and I was surprised to find mode for that linum-relative which is good and customizable. For auto completion I’ve started with auto-complete which works great, but popup window doesn’t look beautiful. Also “smart-tab” mode is available.

emacs popup

Buffer List is kind of built-in buffer explorer in Emacs you can open it with C-x C-b

buffer list

And for Ack I’ve just installed ack plugin. list-packages

Basically you have mode/packages for everything:

  • Rails with rinari
  • Clojure mode
  • Paredit mode
  • Ruby mode
  • YAML mode
  • SML mode
  • Haskell mode
  • Cucumber with feature-mode
  • Zencoding mode

I’ve spent one single day to setup my Emacs environment and I feel myself pretty comfortabe. Which is amazing. Let’s see if it helps me to increase my productivity.

PS: Emacs crash course

  • Close Emacs: C-x C-c
  • Open file: C-x C-f
  • Swith “split”: C-x o
  • Make horizontal “split”: C-x 2
  • Make vertical “split”: C-x 3
  • Kill buffer: C-x k

Peace!

In Clojure we have two nice macros if-let and when-let.

1
2
3
4
5
6
7
8
(if-let [a ...]
  (inc a)
  0)

; or we can use `when-let` when we don't have `else` branch

(when-let [a ...]
  (inc a))

but unfortunately we can’t pass more than two binding forms to these macros, and emulate the behavior of Scheme’s and-let or kind of maybe monad.

I mean smth like that:

1
2
3
4
5
(and-let [a 1 b 2]
         (+ a b)) ; => 3

(and-let [a 1 b nil]
         (+ a b)) ; => nil

It isn’t really hard to implement it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
(defmacro and-let [bindings expr]
  (if (seq bindings)
    `(if-let [~(first bindings) ~(second bindings)]
       (and-let ~(drop 2 bindings) ~expr))
     expr))

(use 'clojure.walk)
(macroexpand-all '(and-let [a 1 b 2]
                           (+ a b)))

; (let* [temp__3971__auto__ 1]
;   (if temp__3971__auto__
;     (let* [a temp__3971__auto__]
;       (let* [temp__3971__auto__ 2]
;         (if temp__3971__auto__
;           (let* [b temp__3971__auto__]
;             (+ a b))
;           nil)))
;     nil))

But we could do some improvements here: check count of binding form (should be even), implement else clause, probably find a better name, implementation.

I’m not really sure about else clause, it can be very useful, but it sounds weird to have else part with and-let name. I thought about if-let* and when-let* names, it looks idiomatic for other Lisps but not for Clojure I think.

Wdyt?

PS. Another option is use the maybe monad from algo.monads but it’s extra dependency for relatively small amount of code (if you don’t plan use monads really often) and slightly different behavior.

Peace!

Whilst experimenting with clj-webdriver and writing social-phobia I have created an interesting macro and would like to share it with you and get some feedback.

Lets write some simple script, log in to GitHub

1
2
3
4
5
6
(set-driver! {:browser :firefox})
(to "https://github.com/login")
(input-text "#login_field" (auth :login))
(input-text "#password" (auth :pass))
(click {:xpath "//input[@type='submit']"})
...

If we have wrong URL or don’t have an element on the page, we basically get that:

1
NullPointerException   clojure.lang.Reflector.invokeInstanceMethod (Reflector.java:26)

In a different way we can get the same result like this:

1
2
3
4
5
6
=> (def el (find-element {:css "#login_fiel"}))
#'user/el
=> el
#clj_webdriver.element.Element{:webelement nil}
=> (input-text el "asd")
NullPointerException   clojure.lang.Reflector.invokeInstanceMethod (Reflector.java:26)

Awesome. But I would like to receive more useful messages if GitHub changes URL or IDs of HTML elements. Let’s make our code “safer”:

1
2
3
4
5
6
7
8
9
10
11
12
13
(defn error
  "Returns \"\"#uername\" not found\" for e.g."
  [selector]
  {:error (str (first (vals selector)) " not found")})

(defn safe-find-element
  "Find the element, if the element is found, call the f,
  if not return a map with an error."
  [selector f]
  (let [el (find-element selector)]
    (if (:webelement el)
      (f el)
      (error selector))))

It means if we find an element we call function with that element, if not we return error which looks like {error: "#signin-email not found"}. Nice, but not so useful so far. Let’s wrap click and input-text functions in this wrapper.

1
2
3
4
5
6
7
8
(defn- safe-input-text [selector text]
  (safe-find-element selector
                     #(-> %
                        clear
                        (input-text text))))

(defn- safe-click [selector]
  (safe-find-element selector #(click %)))

Let’s see how it works:

1
2
=> (safe-input-text {:css "#login_fiel"} "asd")
{:error "#login_fiel not found"}

And try to rewrite our code:

1
2
3
4
5
(set-driver! {:browser :firefox})
(to "https://github.com/login")
(or (:error (safe-input-text {:css "#login_field"} (auth :login)))
    (:error (safe-input-text {:css "#password"} (auth :pass)))
    (:error (safe-click {:xpath "//input[@type='submit']"})))

Hm, it’s not so DRY.

1
2
3
4
=> (do-unless :error (safe-input-text {:css "#login_field"} (auth :login))
                     (safe-input-text {:css "#passwor"} (auth :pass))
                     (safe-click {:xpath "//input[@type='submit']"}))
{:error "#passwor not found"}

Much nicer. But how is it supposed to work? Tada!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
(defmacro do-unless
  "
  Evaluates the expr if the condition which was called
  with result of previous expression returned false.

  Examples:
  =========

  (do-unless nil? (println 1) (println 2))
  1
  nil
  (do-unless nil? (do (println 1) 1) (println 2))
  1
  2
  nil"
  ([condition expr & exprs]
   `(let [r# ~expr]
      (if (~condition r#)
        r#
        (do-unless ~condition ~@exprs))))
  ([condition expr]
   expr))

Macroexpand:

1
2
3
4
5
6
7
8
9
10
(macroexpand '(do-unless :error (safe-input-text {:css "#login_field"} (auth :login))
                     (safe-input-text {:css "#passwor"} (auth :pass))
                     (safe-click {:xpath "//input[@type='submit']"})))

(let* [r__1016__auto__ (safe-input-text {:css "#login_field"} (auth :login))]
  (if (:error r__1016__auto__)
      r__1016__auto__
      (social-phobia.core/do-unless :error
                                    (safe-input-text {:css "#passwor"} (auth :pass))
                                    (safe-click {:xpath "//input[@type='submit']"}))))

Basically this macro recursively produces, a set of nested let and if expressions.

  1. Cache result of expression
  2. Check is’t map with :error message or not
  3. If yes, returns that map
  4. If not start this cycle for next expression

Nice, also it should be faster than catch exceptions and also we don’t produce any extra function calls like we do with monads. I think this macro is pretty much fun for this kind of code with a purely imperative nature.

Wdyt?

Peace!

In this note I would like to describe current situation of dealing with templates in Clojure. We have four most known options:

Let’s start with Fleet. Fleet is pretty similar to old ERB or JSP way of working with templates:

1
<p><(post :body)></p>

In fact it’s not so popular in Clojure world probably because main philosophy of Lisp is “code as data”. And it’s also true for templates. It’s where Hiccup shines:

1
[:p (post :body)]

As you can see, it’s just Clojure vector, first element of this vector is tag name and second one is content. You can add attributes to the tag:

1
[:link {:href "www.example.com"} "Example"]

We can easily make abstraction on it and keep it as a helper:

1
2
3
(defn link [href name] [:link {:href href} name])
(link "www.example.com" "Example")
; => [:link {:href "www.example.com"} "Example"]

For converting it to html you need to pass it to html function:

1
2
(html (link "www.example.com" "Example"))
; => "<a href=\"www.example.com\">Example</a> "

You can make your own collection of helpers and partials which will be easy to embed in your code. lso you can find basic low-lewel helpers as link-to and form-to and so on in Hiccup itself. Hiccup is quite popular in Clojure comunity and it’s used as part of Noir framework. You don’t have to write Hiccup templates by yourself if you already have HTML file from a designer, there are some tools which can help you to convert HTML file to Hiccup.

If you are sceptic about all this stuff like "code as data" in templates you’re able to choose Clostache. It’s just Mustache implementation in Clojure. I think you already know that. This how it looks in Clojure.

1
(render "Hello, !" {:name "Felix"})

Also we have some pretty interesting approach which calls Enlive, it’s similar to XSLT transformation, but instead of noisy XML we have Clojure which is Lisp which is executable XML :) The main idea is keep our html for a designer. Just do nothing with it. No ERB templates, Mustache or any other templates. Just plain HTML and transformations. There is a little bit more code for explanation how it works that is why I’ve placed this code to the gist.

I think it will be unuseful try to describe pros and cons of each of these template libraries, because it’s really depends on which process you use to work with your templates.

Also there is fifth hidden option is use templating on the front-end :)

Peace!

Python was invented as a language for a education, at least partially. And now this language is quite popular and used by many companies and people. And also Python influenced on many languages like for example Ruby or Groovy.

But in functional world we still don’t have own Python, a simple language with the dynamic typization and less noisy syntax. You say Scheme, SICP cources and etc. But for some people LISP’s syntax isn’t a synonym for less noisy.

I think, we need a simple functional language with the dynamic typization, a compact syntax without noise.

Choose first functional language

Lisp Without Parentheses

Peace!

What is it?

  • CoffeeScript is a little language that compiles into JavaScript.
  • The golden rule of CoffeeScript is: “It’s just JavaScript”.

More info in README

When I saw CoffeeScript first time it looks weird: ‘:’ instead of ‘=’ and other strange things. And I wasn’t good about that. But things change and opinions of people too. Now I have very positive opinion about CS not only because CS makes code less noisy, more structured, more readable and less buggy, mostly because ECMAScript and CoffeeScript evolve together. And it makes CoffeeScript not “Yet another language that compiles to JavaScript”. CS has big influence on future and present of ECMAScript, I think. Below I have some examples(it’s not actually examples, just some links to CS website) of features that will be provided in ES6(in future version of ECMAScript specification) and these features already implemented in CS, some of them was borrowed from CS. I think, it’s awesome because we can just use nice features NOW. Also CoffeeScript provides big portion of syntax sugar(short functions, optional return, ranges, additional operators, string interpolation and etc) and fixes some bad parts of JavaScript:

Fixes

  • Problems with global scope (each file wraps to anonymous function)
  • Problems with weak typization (CS internally always uses === operator)
  • Awkward semicolons (CS has indentation syntax)

Features

Some features that will be in ES6/ES.next/ES Harmony and that already exist in CoffeeScript:

Links

Peace!

:skip attribute/key was released in PaperTrail 2.4.1 What are the differences between :ignore and :skip? For example we have Article model with ignored title field and skipped file_upload field:

1
2
3
4
class Article < ActiveRecord::Base
  has_paper_trail :ignore => :title,
                  :skip   => :file_upload
end

Create empty article object, initial version’ll be created:

1
2
3
4
5
>> a = Article.create
>> Article
=> Article(id: integer, title: string, content: string, file_upload: string)
>> a.versions.count
=> 1

If we update ignored title attribute, version won’t be created. If we update non-ignored content column, version’ll be created and we’ll have stored changes of object in object_changes column that available through changeset attribute.

1
2
3
4
5
6
7
8
9
10
>> a.update_attributes :title => 'Title'
>> a.versions.count
=> 1
>> a.update_attributes :title => 'New Title', :content => 'Content'
>> a.versions.count
=> 2
>> a.versions.last.changeset
=> {"content"=>[nil, "Content"]}
>> a.versions.last.reify
=> #<Article id: 1, title: "Title", content: nil, abstract: nil, file_upload: nil>

As we see ignored title column not stored in changeset but it stored in dumped object. But there are some cases when we don’t need to store some columns in dump object by various reasons. For these cases :skip key has been created. :skip and :ignore work identically, but :skip doesn’t store data of skiped columns in object dump. That’s it.

Information about attributes tracking you can find in paper_trail PaperTrail README (Choosing Attributes To Monitor) on GitHub.

Issue about :skip on GitHub.

Peace!

Why 2.0?

In this version we moved Underscore.string library to separate namespace _.string for solve name conflicts with Underscore library. There are some functions that available in both libraries, for ex. include and reverse. In 1.1.6 and lower Underscore.string provided includes function, but we decided that two function include and (includes or includeString) in one namespace and with same functionality but one function for collections another for strings, it’s a little bit ugly.

Do we always need to write _.string?

Nope. Underscore.string provide exports function _.string.exports(), this function returns only non-conflict functions and we can mix in these functions to Underscore scope if you want.

1
2
3
4
5
6
7
8
9
10
11
_.mixin(_.string.exports());

// Access to Underscore.string and Underscore functions
_.include([1,2,3], 1)
_.trim('  asd  ')

// Access to conflict Underscore.string functions
_.string.include('foobar', 'bar')
// or
_.str.include('foobar', 'bar')
// "str" it's just alias for "string"

Problems

We lose two things for include and reverse methods from _.string:

  • Calls like _('foobar').include('bar') aren’t available;
  • Chaining isn’t available too.

But if you need this functionality you can create aliases for conflict functions which will be convnient for you.

1
2
3
4
5
6
7
_.mixin({
    includeString: _.str.include,
    reverseString: _.str.reverse
})

// Now wrapper calls and chaining are available.
_('foobar').chain().reverseString().includeString('rab').value()

Standalone Usage

If you are using Underscore.string without Underscore. You also have .string namespace for it. And current version number you can find through VERSION constant .string.VERSION. If you want you can just reassign _ variable with _.string

1
2
3
_ = _.string

_.VERSION // => 1.2.0

Node.js Installation

1
npm install underscore.string

Standalone usage:

1
var _s = require('underscore.string');

Integrate with Underscore.js:

I recommend you this way for integrating with Underscore.js:

1
2
3
4
5
6
7
8
9
10
var _  = require('underscore');

// Import Underscore.string to separate object, because there are conflict functions (include, reverse, contains)
_.str = require('underscore.string');

// Mix in non-conflict functions to Underscore namespace if you want
_.mixin(_.str.exports());

// All functions, include conflict, will be available through _.str object
_.str.include('Underscore.string', 'string'); // => true

Upgrade

In new version function includes has been removed, you should replace this function by .str.include or create alias .includes = _.str.include and all will work fine.

Peace!

1. Changeset

From PaperTrail 2.2.7 release you can find a new method of Version instances, called changeset. PaperTrail doesn’t have diffs mechanism inside, but now if you have object_changes column in versions table (it can be generated automatically if you install PaperTrail with –with-changes option) it will store Rails’ changes of dirty objects.

1
2
$ rails g paper_trail:install --with-changes
# or manually add `object_changes` column in your `versions` table
1
2
3
4
>> widget = Widget.create :name => 'Bob'
>> widget.versions.last.changeset                # {}
>> widget.update_attributes :name => 'Robert'
>> widget.versions.last.changeset                # {'name' => ['Bob', 'Robert']}

More information about Diffing Versions you can find in PaperTrail README on GitHub.

2. Flexibility in naming of methods

There are some situations when methods version and versions are already busy by other associations or smth. In this case we can change the names of these methods in our application (but sometimes it’s time-consuming) or we can configure these methods in PaperTrail like that:

1
2
has_paper_trail :versions => :paper_trail_versions,
                :version_name => :paper_trail_version

3. Add :on option

With this option we can configure what events we need to track. For example, we don’t need to track create events:

1
has_paper_trail :on => [:update, :destroy]

4. Without Versioning

In some cases some action/actions must be executed without versioning. Now PaperTrail has simple wrapper for this case:

1
2
3
4
5
6
7
8
# Executes the given method or block without creating a new version.
def without_versioning(method = nil)
  paper_trail_was_enabled = self.paper_trail_enabled_for_model
  self.class.paper_trail_off
  method ? method.to_proc.call(self) : yield
ensure
  self.class.paper_trail_on if paper_trail_was_enabled
end

Usage:

1
2
3
4
5
6
7
# With method name
@widget.without_versioning :destroy

# or with block
@widget.without_versioning do
  @widget.update_attributes :name => 'Ford'
end

5. Attr Accessible

Now we need to use attr_accessible if we want to store some meta info in versions table. Example of meta information from PaperTrail README:

1
2
3
4
5
6
7
8
9
class Article < ActiveRecord::Base
  belongs_to :author
  has_paper_trail :meta => { :author_id  => Proc.new { |article| article.author_id },
                             :word_count => :count_words,
                             :answer     => 42 }
  def count_words
    153
  end
end

In this case author_id, word_count and answer are meta, and we need to have these columns in versions table. And also we need to add these attrs to attr_accessible

Peace!