capistrano on sinatra

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.

Swimming in Zurich: "Züribad"

Posted by alexis reigel on April 25, 2011

My first android application is a utility app about all public swimming baths in Zurich. It shows the current water temperature for each bath and additional information is available too, such as address and routing info (how to get there by public transportation). Google map integration provides a geographical overview of the baths.

The app is freely available in the android market. The source code is hosted on Bitbucket.

Share on min.us from windows explorer context menu

Posted by alexis reigel on February 19, 2011

There's a new tool for the file sharing service min.us that makes it really easy to share files. The tool provides a context menu entry in the windows explorer and a simple user interface to upload the files and provide you with the share url.

The tool is on my project page and on github.

Windows console: spawn new process

Posted by alexis reigel on January 19, 2011

Under linux spawning a new process is as easy as appending an & to the command. In windows it's not (obviously). I pretty quickly found out about the start command. Not as elegant as the linux version, but still pretty intuitive. Or, wait, not? It took me half a decade to find out how to use it properly.

First i had a look at the help output, which can be invoked by the switch /?. I'm not 100% sure, but i have in mind that this switch isn't really standardized, i think I also had to use /h or /help in the past. Anyway, that's not the sad part yet.

Reading through that, all you have to do is call start my_command. Easy huh? No. It's not.

After digging around this article lead me to the solution: "title: Text for the CMD window title bar (required)". Title! Required!
Let me say that again. Title! Required!
First thought: Why? Why is a title required? A title is clearly something optional, especially when you're starting a GUI application.
Second thought: Why? Why is that "required" not stated as such in the help output? Not the slightest hint in the help output. And furthermore, isn't it a convention that required parameters are NOT surrounded by brackets? Don't brackets mean "optional"? Apparently, in the windows tooling environment all this does not apply.

I know, windows is a GUI centered OS, and therefore the console didn't evolve as nicely as it did in other OS's. Nevertheless, every time I have to work on a console or write a batch file it gives me the creeps. Everything is so unbelievably clumsy. At least I found out about the Console project, which is a pretty decent replacement for the windows console. Copy/paste works as desired with keyboard shortcuts and you can resize the window. Resize the window! How cool is that! But that's a different story...

DataGridView with an object data source

Posted by alexis reigel on September 04, 2010
For my Batch Replacer I am using a DataGridView with an object data source, meaning that I have a collection class that holds the data to be displayed. At first that class inherited from a usual List<T>, which led to the problem that the data binding wasn't two-way. As soon as I bound data to the DataGridView, it wasn't possible to add any new rows to it in my user interface. After some research I found out that instead of using a normal List<T> I was supposed to use a BindingList<T>. Using that the binding is two-way, and the user interface is normally editable and new rows can be added. Also, of course, all modifications done in the user interface are reflected in the object (meaning e.g. that when a new row is added, the object data source contains a corresponding entry).

Replace as in batch replace

Posted by alexis reigel on September 03, 2010

So I once again needed to replace several patterns in multiple files with something new... Instead of doing this all in my favorite text editor by using repeatedly find/replace, I decided that something more handy was needed. Of course I could have done all that replace stuff with xslt, but hey, who actually likes xslt.

The result of my disapproval of the above mentioned options is the Batch Replacer. As always it is released under the gpl. I also used git for the first time and published the source code on github.

Navigate to those... out of the box with firefox

Posted by alexis reigel on March 30, 2010

Ok well, this doesn' seem to be new at all, but nevertheless I missed that. Firefox has the great functionality to assign shortcuts to certain bookmarks and supply a parameter to the URL. This leads to really great quick searches (aka. the art of bookmarking).

What I have now are shortcuts to all my often used search sites. To search in wikipedia e.g. I type CTRL + L (shortcut for placing the cursor in the URL bar in firefox), then type wp asdf and there I go.

 

I guess this fact renders my previously posted quick link access tool obsolete...

Navigate to those URLs over and over again...

Posted by alexis reigel on May 15, 2009

I've written a tool that allows to define commonly used URLs for repeated access, varying only by a defined parameter-part. When you call one of those URLs, you just need to pass a parameter and it opens in the browser. That way you get quick access to often used URLs, e.g. your preffered search engine, your ticketing system or whatever. For even faster access the URLs are bound to predefined global hotkeys.

More infos can be found on the project page.

Screenshot of the main application's window

Nullable average in LINQ

Posted by alexis reigel on October 12, 2008

The following code is one possibility (there may be more elegant solutions to this) to handle a nullable average from a linq query. The problem arises when the linq query does not return a result, thus the average being null. If you don't use a nullable type, you'll get an exception. To get a nullable average from an integer value you'll need to provide a transform function to the Average funtion.

 
double? nullableAverage = 	
    (from m in dataContext.Moods 	 
	join g in dataContext.Groups on m.GroupGUID equals g.GUID 	 
	where g.GUID == groupGUID 	 
	select m.Level) 	
	.Average<int>(x => new double?(x));  
int average = (int)Math.Round(nullableAverage.HasValue ? nullableAverage.Value : 0, 0);  
// ... 
 

Custom application settings

Posted by alexis reigel on June 28, 2008

Within a c# winform application I needed to store a generic collection to my settings, which I found out was not possible out of the box. It is possible though to set the required type in the properties designer dialog, but the serialization's output is always nothing.

On my research on the internet for a solution i stumbled upon the post Tips for C# .NET Software Developers, which described that the attribute [SettingsSerializeAs(SettingsSerializeAs.Binary)] was required for the settings property, and to set it accordingly in the Settings.Designer.cs file. The problem here is that modifying designer generated code file is not the best of all ideas, as the manual changes are overwritten every time the settings are modified by the designer. Thus, I followed the msn article on how to create application settings, which told me to create a custom settings class. The drawback with this solution is that I now have two settings classes, and not only one single to cover it all.

Here's an example of the settings class. Note the use of the SettingsSerializeAs attribute, as it is the key to the successful serialization.

 
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;

namespace Koffeinfrei
{
    /// <summary>
    ///   This class provides extended settings. Use this class for types that need to have special     
    ///   attributes for serialization, that cannot be set using the config designer dialog.
    /// </summary>
    internal class ExtendedSettings : ApplicationSettingsBase
    {
        private static readonly ExtendedSettings defaultInstance =
            ((ExtendedSettings) (Synchronized(new ExtendedSettings())));

        /// <summary>
        ///   Returns the default instance of this class.
        /// </summary>
        /// <remarks>
        ///   Get the value of the <see name="defaultInstance" /> member.
        /// </remarks>
        public static ExtendedSettings Default
        {
            get { return defaultInstance; }
        }

        /// <summary>
        ///   The <see cref="SomeCustomClass" />s stored in the user scoped settings.
        /// </summary>
        /// <remarks>
        ///   Get / set the value of the <c>CustomClasses</c> property.
        /// </remarks>
        [UserScopedSetting]
        [DebuggerNonUserCode]
        [SettingsSerializeAs(SettingsSerializeAs.Binary)]
        public Queue<SomeCustomClass> CustomClasses
        {
            get { return ((Queue<SomeCustomClasses>) (this["CustomClasses"])); }
            set { this["CustomClasses"] = value; }
        }
    }
}
 

Rubyblood 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);   
	}
); 

Rubyblood 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.

Too many parameters?

Posted by alexis reigel on October 06, 2006

Today I came across an interesting fact about java (referring to the programming language, not the island). But first things first. You may not be interesting in the previous history but I'll tell it anyway.
During my diploma work (that will be finished in one week by the way) I had to generate some classes invoking the wsdl2java parser. I won't explain what that parser is about. Anyway, I invoked the parser on the amazon web service which got me an interesting error. ItemAttributes.java:538: too many parameters So I counted them and I got 261 arguments. That made me wonder how many arguments were actually allowed for a method in java. I searched the java forums and mailinglist and found the answer in the Java Virtual Machine Specification. The following summarizes the facts I was interested in.
"Java limits the number of method parameters to 255 or 254 or less if parmeters are of type long or double. The 255 method parameter limit is for static methods and 254 for non static methods." And some more limitation facts for that matter.

  • method bytecode: 65,535 bytes
  • local variables: 65,535 (each long or double counts as two variables)
  • fields: 65,535 (does not include inherited fields)
  • methods: 65,535 (does not include inherited methods)
  • method parameters: 255 (each long or double counts as two parameters)

I hope that no programmer will ever get even close to those limits. Otherwise the class design should definitely be reconsidered. Anyway, I'm positive that I'm not going to ever see a method that has more parameters than this one...

The white beverage

Posted by myself on September 23, 2006

At my workplace we have a coffee automat which I didn't consider more than just being my coffee supplier. Yesterday I noticed though that it has some peculiar beverage on offer. It's called "Weisses Getränk mit Kaffee" (that was German), and for the English speaking folks the translation would be like "White beverage with coffee" (that was English). That really sounds ominous. Maybe I don't want to try that one...
By the way, sorry for the crappy fotograph, the camera of my cellphone lacks almost everything that would make it a good camera.

White beverage

Random Quote

Es wird immer alles gleich ein wenig anders, wenn man es ausspricht. (Hermann Hesse)

» ...

koffeinfrei on identi.ca

icon
2012-02-01 09:13:03
wrote a short post about capistrano deployment for a sinatra app, summing up the scattered documentation... http://identi.ca/url/65862527
icon
2012-01-27 16:25:29
stop internet #censorship, sleazy bastard #acta http://www.stopp-acta.info, it's not over #sopa
icon
2012-01-27 14:04:03
wat! on ruby and javascript. hilarious: http://identi.ca/url/64793583
icon
2011-12-29 23:23:20
nice: "git meld" enables "git diff" in external diff viewer http://identi.ca/url/63405956
icon
2011-12-04 21:29:39
test runs & cats & rainbows. genius. http://identi.ca/url/61578085
icon
2011-11-23 22:28:55
vimtutor: a really great intro to vi(m).
icon
2011-11-23 22:25:40
RT @thoughtbot "The vim learning curve is a myth." http://t.co/mgBCxJQW
icon
2011-11-16 13:36:29
@Spotify services that require a facebook account shall all die a painful death!
icon
2011-10-31 22:29:17
"Wish you could write your Ruby in XML? Has the fact that Ruby is not “enterprise” got you down?" http://identi.ca/url/56208722
icon
2011-10-14 21:28:44
Attending "A Free Digital Society - Richard Stallman" http://identi.ca/url/54104004
icon
2011-09-30 15:29:15
... and the standalone .net library too: http://ur1.ca/593sg
icon
2011-09-30 15:28:05
gave up waiting for the broken minus api v1 to get fixed, updated the library myself -> new minus share version: http://ur1.ca/593q3
icon
2011-09-28 21:08:31
"User-Led Innovation Can't Create Breakthroughs; Just Ask Apple and Ikea" http://identi.ca/url/39222176
icon
2011-09-28 20:38:50
"Logging out of Facebook is not enough" http://nikcub.appspot.com/logging-out-of-facebook-is-not-enough
icon
2011-09-22 07:10:58
nice mobile emulator (chrome extension) http://ripple.tinyhippos.com/download
icon
2011-09-15 11:03:48
"hello world" in trollscript :-) "Because Brainfuck is so last year, right?": http://tinyurl.com/3twg2xp
icon
2011-09-10 21:31:07
8. bottom line from @frontendconfch #fec11: auto-reload firefox page with guard-mozrepl https://github.com/guard/guard-mozrepl
icon
2011-09-10 21:27:59
7. bottom line from @frontendconfch #fec11: no more inspiration @smashingmag http://ustre.am/:19ZEP
icon
2011-09-10 21:27:45
6. bottom line from @frontendconfch #fec11: css3 for backgrounds @LeaVerou http://ustre.am/:19Z2a (47:22)
icon
2011-09-10 21:27:28
5. bottom line from @frontendconfch #fec11: more cursors in css3 @LeaVerou http://ustre.am/:19Z2a (32:55)
icon
2011-09-10 21:27:05
4. bottom line from @frontendconfch #fec11: css3 gradients @LeaVerou http://ustre.am/:19Z2a (36:10)
icon
2011-09-10 21:26:47
3. bottom line from @frontendconfch #fec11: custom checkboxes in css3 @LeaVerou http://ustre.am/:19Z2a (28:18)
icon
2011-09-10 21:26:27
2. bottom line from @frontendconfch #fec11: javascript unit testing with buster.js @cjno http://ustre.am/:1a01x
icon
2011-09-10 21:25:52
1. bottom line from @frontendconfch #fec11: make designs in the browser, not in photoshop! @bastianallgeier @LeaVerou @jng5 @smashingmag
icon
2011-08-25 21:34:27
Andrew Lawrence: "I admire these phone hackers. I think they have a lot of patience. I can't even be bothered to check my OWN voicemails."
icon
2011-08-25 21:02:59
Why MSTest is the IE6 of unit test frameworks: http://osherove.com/blog/2011/8/24/why-mstest-is-the-ie6-of-unit-test-frameworks.html
icon
2011-08-15 11:41:28
great advertising... http://www.youtube.com/watch?v=rJRiz9aSHFQ
icon
2011-08-05 10:43:52
My diploma work was published as a book: http://tinyurl.com/3ujy8db. A bit outdated matter though...
icon
2011-07-20 14:28:24
how standards proliferate: http://xkcd.com/927/
icon
2011-05-10 12:06:13
#minusshare was added to the official min.us tools page: http://min.us/pages/tools
icon
2011-02-19 01:25:04
Share files on min.us from windows explorer context menu: https://github.com/koffeinfrei/MinusShare
icon
2011-02-01 21:32:52
[zueribad-wintray] http://bit.ly/eBD2LT lex - fixed license file
icon
2011-01-30 19:46:28
[zueribad-wintray] http://bit.ly/dZ02k8 Alexis Reigel - * release 0.1.3
icon
2011-01-30 19:46:24
[zueribad-wintray] http://bit.ly/h30HJw Alexis Reigel - * updated icon * added license and autostart to setup
icon
2011-01-29 23:05:38
[zueribad-wintray] http://bit.ly/fLoUAB Alexis Reigel - * version 0.1.2
icon
2011-01-18 08:12:19
Used to working on a terminal (linux)? Windows console sucks. http://tinyurl.com/23ll4l a pretty decent windows console replacement.
icon
2010-11-30 18:29:10
Jason Fried: Why work doesn't happen at work: http://www.youtube.com/watch?v=5XD2kNopsUs
icon
2010-09-12 13:40:22
[batchreplacer] http://bit.ly/cCYITS koffeinfrei - 3 commits
icon
2010-07-26 11:46:49
Everybody needs a fishbowl: “YouTube - Barry Schwartz: The paradox of choice” — http://www.youtube.com/watch?v=VO6XEQIsCoM
icon
2010-06-18 09:07:19
@kentbrew: what i'm i missing? the #identica-badge doesn't show my entries on http://koffeinfrei.org/
icon
2010-06-16 08:00:30
“YouTube - BP Spills Coffee” — http://www.youtube.com/watch?v=2AAa0gd7ClM
icon
2010-06-01 20:03:29
"The surprising truth about what motivates us”: http://www.youtube.com/watch?v=u6XAPnuFjJc&feature=player_embedded

Ying and Yang

where I am
where I should be
Fork me on GitHub