See the new site: https://postgresisenough.dev
Just to get everyone up to speed; Structs are a great because they provide compile time checks. Compile-time checks are awesome as we can catch errors before we run our application in the run-time. Structs also allow us to make custom data types, and we can implement protocols that amongst other things allow us to tell Elixir how it should enumerate over our data type, or insert items into our data type using Protocols.
| defmodule Flatten do | |
| @doc """ | |
| Flattens a list by recursively flattening the head and tail of the list | |
| """ | |
| def flatten([head | tail]), do: flatten(head) ++ flatten(tail) | |
| def flatten([]), do: [] | |
| def flatten(element), do: [element] | |
| end |
In researching topics for RailsCasts I often read code in Rails and other gems. This is a great exercise to do. Not only will you pick up some coding tips, but it can help you better understand what makes code readable.
A common practice to organize code in gems is to divide it into modules. When this is done extensively I find it becomes very difficult to read. Before I explain further, a quick detour on instance_eval.
You can find instance_eval used in many DSLs: from routes to state machines. Here's an example from Thinking Sphinx.
class Article < ActiveRecord::Base| $ rvm use 1.8.7-p302 | |
| $ wget http://subversion.tigris.org/downloads/subversion-1.6.15.tar.gz | |
| $ tar -xzf subversion-1.6.15.tar.gz && cd subversion-1.6.15 | |
| $ ./configure --with-ruby-sitedir=~/.rvm/rubies/ruby-1.8.7-p302/lib/ruby --without-berkeley-db | |
| $ make swig-rb && make install-swig-rb | |
| To test things out: | |
| $ irb | |
| ruby-1.8.7-p302 > require 'svn/client' | |
| => true |