Spec for has_many with dependent option

posted by alexis reigel on february 15, 2016

New post on the Panter Blog (the company I’m working for):

blog.panter.ch/2016/01/12/spec-for-has_many-with-dependent-option.html

Idempotent seeds in rails

posted by alexis reigel on august 28, 2015

Guest post on the Panter Blog (the company I’m working for):

blog.panter.ch/2015/08/05/idempotent-seeds-in-rails.html

validate all database records rails task

posted by alexis reigel on march 25, 2014

Sometimes you need to validate all your active record entries in the database. This may happen when you update validations in your models and you want to check which models need an update. Or you have a legacy system that has invalid records. Or some other system wrote to the database (without the rails application’s validation).

Here’s a rake task that validates all database rows for all the ActiveRecord models in your rails application.

namespace :db do
  namespace :data do
    desc 'Validates all records in the database'
    task :validate => :environment do
      original_log_level = ActiveRecord::Base.logger.level
      ActiveRecord::Base.logger.level = 1

      puts 'Validate database (this will take some time)...'

      Dir["#{Rails.root}/app/models/**/*.rb"].each { |f| require "#{ f }" }

      ActiveRecord::Base.subclasses.
        reject { |type| type.to_s.include? '::' }. # subclassed classes are not our own models
        each do |type|
          begin
            type.find_each do |record|
              unless record.valid?
                puts "#<#{ type } id: #{ record.id }, errors: #{ record.errors.full_messages }>"
              end
            end
          rescue Exception => e
            puts "An exception occurred: #{ e.message }"
          end
        end

      ActiveRecord::Base.logger.level = original_log_level
    end
  end
end

And here’s the whole thing as a gist.

fuzzy file matching in vim

posted by alexis reigel on december 13, 2013

Until recently I used command-t as the mechanism for opening files. It was always working great for me, and apart from the installation, which is a bit of a hassle because it’s written in ruby, I was very happy with it. There was only one feature missing: Word boundary matching by using uppercase characters.

I was playing with the thought of contributing that feature to command-t, but then Gary Bernhardt came along and put selecta out there:

A fuzzy text selector for files and anything else you need to select.

He even provides a simple script that provides fuzzy file matching in vim.

So… let’s extend that really nice and simple script with my desired word boundary matching, I thought. And I did exactly that.

What my extension does is this:

Uppercase characters in the query must match a word boundary. Word boundaries are pascal and camel cased words and the characters ‘/’, ‘\’, ‘_’, ‘-’, ‘.’ and whitespace. (“FooB” will match “foo/bar” and “fooBar” but not “foobar”)

For the use case of fuzzy file matching in vim the change allows to search very quickly for specific paths. If we want to search e.g. for a rails model named foo, we could enter “AMFoo”, which would match the path “app/models/foo.rb”, but not “app/controllers/myfoos_controller”. If we searched just for “amfoo”, the latter would be matched as well.

string variable interpolation from file in ruby

posted by alexis reigel on december 17, 2012

Sometimes you want to interpolate your variables from a dynamic string, e.g. some settings from a yaml file. The top three options are:

I’ll show the third option here as:

Ruby has string formatting support and a very handy % operator. This enables us to replace certain parts of our config at runtime with the actual value, like this:

"foo = %{foo}" % { :foo => 'bar' }

Metaflop serves once again as a sample application. The following shows the perl command to generate some parts of our fonts (simplified):
config.yml:

font_otf: perl mf2pt1.pl --family=%{fontface} --nofixedpitch --fullname="%{fontface} %{font_hash}" font.mf

Assuming we have a “config” variable that holds all the values defined in yaml we can do:

config.font_otf % {
  :fontface => 'Bespoke',
  :font_hash => '234sdof23nsf'}

# => perl mf2pt1.pl --family=Bespoke --nofixedpitch --fullname="Bespoke 234sdof23nsf" font.mf

The operator accepts literals and arrays as arguments as well, but I like the named parameters style best. This way, there is an obvious connection between the placeholder and its value.

sinatra with bourbon

posted by alexis reigel on march 24, 2012

If you search the web for “bourbon sinatra” you get a whole lot about Frank Sinatra and his drinking habits. But that’s not what this post is about.

How to use bourbon scss mixins with sinatra is not documented on their project page. So here’s my short setup.

The following is standard, from their documentation.

$ gem install bourbon # or better, add to use Gemfile and use bundler
$ cd views/scss
$ bourbon install

Next, import bourbon in your main scss file (as first statement).

@import 'bourbon/bourbon';

The following is the important and the undocumented part, specifically for sinatra. You need to require the ruby libraries in your scss route.

get '/assets/css/:name.scss' do |name|
  require './views/scss/bourbon/lib/bourbon.rb'
  content_type :css 
  scss name.to_sym, :layout => false
end

static vs dynamic vs strong vs weak vs duck typing

posted by alexis reigel on march 19, 2012

Here’s my take at clearing up the confusion about the most common type systems used in programming.

I often hear how static and strong typing are used as synonyms. These two are however quite different systems. The same applies to dynamic and weak typing. For instance, a programming language can be both dynamically and strongly typed, but not dynamically and statically. Ruby is an example of a dynamically and strongly typed language.
Ok, I guess now it’s the time to elaborate.

static vs dynamic

  // example in c#

  string s = "asdf";
  # example in ruby

  s = "asdf"

strong vs weak

  # example in ruby

  "1" + 1 # TypeError
  // example in javascript

  "1" + 1 // "11"

duck typing

Duck typing is a style of dynamic typing.With duck typing, the set of methods and properties determine the valid semantics of a class, instead of inheritance from a specific class or implementation of an interface.
“When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.”
This means that we actually don’t care if the class we’re using is actually of a certain type, as long as it provides the methods or properties we’re interested in.
The term duck typing comes from python, but ruby is also very known for this behaviour.

sinatra on capistrano

posted by alexis reigel on january 31, 2012

Capistrano is really great for deployment. The documentation however is somewhat scattered. The capistrano wiki has a more or less useful From The Beginning instruction and a Getting Started that doesn’t quite get you started.
However, the instructions on github are actually a very good starting point. Neverthelesse I want to show my sample here that has two additions to the one in the github help.

  1. Multistage support (i.e. staging and production server)
  2. Custom task to upload a config file

For further reading I recommend the Capistrano Handbook.

I assume that you’ve setup capistrano as described in the github help. The one thing I suggest is to ignore the part where the password is stored in the file. I highly advise to use ssh agent forwarding instead.

ssh_options[:forward_agent] = true # use local ssh key
set :user, "deployer"

Let’s setup multistage:

require 'capistrano/ext/multistage'
set :stages, %w(production staging)
set :default_stage, "staging"

Also, on most deployment server you may not have rights to sudo:

set :use_sudo, false

As I’m assuming you’re using passenger mod_rails:

namespace :deploy do
  task :start do ; end
  task :stop do ; end
  task :restart, :roles => :app, :except => { :no_release => true } do
    run "#{try_sudo} touch #{File.join(current_path,'tmp','restart.txt')}"
  end
end

The last part uploads our configuration file to the server. This configuration contains user and password for the database login. We don’t store that in the source code repository.

namespace :config do
  task :db do
    upload('db.yml', "#{deploy_to}/current/db.yml")
  end
end

before "deploy:restart", "config:db"

The whole capistrano configuration file is on github.

ruby blood through your .net veins with a vengeance

posted by alexis reigel on june 28, 2008

In my last blog entry i totally neglected the fact that there are lamda expressions. This nice little C# 3.0 feature makes anonymous methods much more readable. With that in mind, we can make our Times method much nicer.

Example 1: Ruby style iterator with lambda expression

2.Times( number => { Console.WriteLine("> " + number); } ); 

Compared to the former syntax, it increases readability considerably.

Example 2: Ruby style iterator with bare delegate

2.Times( 
    delegate(int number)   
	{     
	    Console.WriteLine("> " + number);   
	}
);

ruby blood through your .net veins

posted by alexis reigel on april 07, 2008

No other programming language has been syntactically as nice as ruby. Ruby is fully object oriented, most other languages appear to be not so consistent, especially when it comes to primitive data types vs classes. In ruby, everything is an object, in many other object oriented language this is not the case. Most of them have primitive data types besides classes, which means that you cannot necessarily call methods on all types. And, ruby’s syntax lets you write much functionality with little code.

But ruby is not alone, .NET is catching up a bit with each release. Now with version 3.5, M$ has introduced extension methods. They allow to extend classes dynamically, without the need to subclass.

My first thought was, let’s .NET look more like ruby, in respect to its fully ojbect oriented data types. In ruby you could write 2.times {...} to create a neat loop. In .NET, this is now possible too! You just have to write a static class with static methods, where its first paramater is prefixed with this. The first parameter defines the class type the method is added to. That’s it. You can even overload methods. And, the newly created methods popup in intellisense!

Extension methods - intellisense

2.Times? The rubyists among you know where this is going…

Example 1: Extend String class

Let’s extend the string class with an overloaded Replace-Method that performs a regexp replace.

public static class StringExtensions
{
    public static string Replace(this string stringRef, string pattern, string replace, RegexOptions options)
    {
        return Regex.Replace(stringRef, pattern, replace);
    }
}

Call it like this:

public class Program
{
    private static void Main(string[] args)
    {
        string stringOrig = "this is stupid.";
        string stringReplaced = stringOrig.Replace(@"(this) is ([^\.]+)\.", "$1 is not $2!", RegexOptions.None);
        Console.WriteLine(string.Format("Orginal string: {0}\nReplaced string: {1}", stringOrig, stringReplaced));
        Console.ReadLine();
    }
}

Pretty neat so far huh? But now, let’s face the 2.times code.

Example 2: Create a ruby style iterator

public static class IntegerExtensions
{
    public delegate void IntegerExtensionsDelegate(int intRef);

    public static bool IsEven(this int intRef)
    {
        return intRef % 2 == 0;
    }

    public static void Times(this int intRef, IntegerExtensionsDelegate invokeMethod)
    {
        for (int i = 0; i < intRef; ++i)
        {
            invokeMethod(i);
        }
    }
}

Let’s call it now:

public class Program
{
    private static void Main(string[] args)
    {
        /* ruby heart beats faster */
        if (2.IsEven())
        {
            Console.WriteLine("Number 2 is even!");
        }
        Console.WriteLine("And now: 2 times loop"); 
        /* ruby heart collapses in bliss */
        2.Times(delegate(int number) { Console.WriteLine("> " + number); });
        Console.ReadLine();
    }
}

The Times method almost looks like a ruby iterator with a block assigned. Instead of having a block, we just pass a anonymous method (aka. delegate) to the Times method, and we pretty much get what we wanted.

If you’re interested in details on the compiler output, you can read about it on Scott Hanselmann’s Computer Zen.