Author Archive

Scala meet up in Århus (DK), 5th of May

April 8, 2010

If you are interested in the Scala programming language + you are around Århus (Denmark) on the 5th of May, then you are invited to participate in the first Scala software developers meetup in Århus.

This free meet up is sponsered by Miracle and 41concepts. We meet at GeekHouse from 5. May. 2010  kl. 15-17 , Rosensgade 22, 2. sal, 8000 Århus C.

Agenda is still open, but we will try to ensure that subjects like Scala 1.7/1.8, Lift, development tools and Java integration will be covered. If you are experienced in Scala and want to contribute with a talk or demo, you are very welcome !

P.S. It is the plan to arrange a similar meet up in Copenhagen at a later time, so don’t worry if you can’t travel on the 5th.

Breaking encapsulation with C# 2.0 partial classes (moved posting)

March 23, 2010

For good or bad partial classes in C# 2.0 allows breaking of encapsulation as this example will show.

In a consulting job I recently ran into an interesting case involving a webservice with several different service methods f1, f2, fn (sample names, not actual names) all taking the same string argument and all returning a string. The user would select an operation name after which my code had to call the named operation on a web service using a standard parameter. Trivial really, if one would do accept bad code like this below, but I don’t:

 String operationName = …
 String arg = …
 Webserviceproxy webserviceproxy = …
 // Warning: Badly coupled code begins here (need to update each time we  add/rename/delete operations).
 switch (operationName) {
 case “f1″: return webserviceproxy.f1(arg); break;
 case “f2″: return webserviceproxy.f2(arg); break;
 }

What is really needed is a method to invoke a webservice method by name, while still using the generated .NET proxy to do the hard soap/http stuff (no time to reinvent a better wheel here). Reflection is one way to do this, but let’s try another type-safe method for this posting, because the technique shown here is quite powerful for all sorts of related problems:

Let’s look at an extract of the generated proxy:

public partial class Webserviceproxy :  System.Web.Services.Protocols.SoapHttpClientProtocol
 {
  …
  public string f1(string arg) {
   object[] results = this.Invoke(”f1″, new object[] {arg});
   return ((string)(results[0]));
  }
  …
 }

and at the inherited SoapHttpClientProtocol:

 public  class SoapHttpClientProtocol : HttpWebClientProtocol {
 
  protected object[]  Invoke(string methodName, object[] parameters) {
 
  }
 
  }

It seems the method “invoke” would fulfil our needs if it was only public (which it isn’t). So what do we do? Certainly we do not want to modify the generated file (and lose our changes each time it is regenerated).

The good news is that Generatedwebserviceproxy is a partial class so we can extend it with the following code. We will place the code in a file safely outside the generated proxy class file:

public partial class Webserviceproxy :  System.Web.Services.Protocols.SoapHttpClientProtocol
 {
  ///
  /// Dynamic operation that allows us to call an operation by name.
  ///
  public string InvokeAny(String operationName, string arg)
  {
   object[] results = this.Invoke(operationName, new object[] {arg});
   return ((string)(results[0]));
  }
 }

The compiler will merge the two class definitions effectively adding a new public InvokeAny method to the generated class. And now we can call our web service calls dynamicly from using InvokeAny:

 String operationName = …
 String arg = …
 Webserviceproxy webserviceproxy = …
 return webserviceproxy.InvokeAny(operationName, arg);

Clearly, easy to do and with better overall code than a “switch” – even though it is not without drawbacks as it breaks encapsulation of the generated proxy.

Post scriptum:
Used the same partial classes trick today to add a common custom interface to two differently generated proxies. I now officially miss this feature in Java (yes, AspectJ can do the thing but it is not a official part of the language).

Recent update and notice:

This post an almost identical copy from my old blog at “http://www.mortench.net/blog” which I will shortly retire for good.

Keeping track of Rails Boot progress

March 2, 2010

Ruby on Rails can take a long time to boot so in some cases it can be useful to provide some kind of progress reporting (f.x. if you are considering using Rails in an embedded application).

RoR does not provide any direct means to monitoring the progress of the boot-process, so a little work is necessary. Changing the ruby source files involved in the boot process is not ideal from a maintenance standpoint and even if one does so, the progress report turns out to be very uneven. The best approach I could come up with was a Kernel hook which keeps track of when files are require‘d. Both easy to do and works surprisingly well for fine-tuned progress reporting.

# Hook into require so that we can track startup progress
module Kernel
 alias org_untracked_require_myAppName require
 def require(file, *extras)
 v=org_untracked_require_myAppName(file, *extras)
 $progress_coordinator.addWorkDelta(1,'Rails required '+file.to_s)
  unless progress_coordinator.nil? || file.nil? || !v
 v
 end
end

Translating models in ruby on rails

July 3, 2009

I had to translate a model in Ruby on Rails. The example (in: http://guides.rails.info/i18n.html#translations-for-active-record-models) was:

activerecord:
  models:
    user: Dude
  attributes:
    user:
      login: "Handle"

Well that didn’t work for me. My only difference was that my model name consisted of two words, so in my yml file I had the following:

activerecord:
  models:
    email_template: Email template
  attributes:
    email_template:
      name: Name
      subject: Subject
      body: Body

But this did not work in the “error_messages_for”. Well the attribute names did, but not the model name that remained untranslated.

After an hour of Googling I didn’t have any answers until I tried to ad a space instead of the “underscore” in the model name. THAT WORKED. So now my yaml file looks like the following. Notice the inconsistencies in the model name!

activerecord:
  models:
    email template: Email template
  attributes:
    email_template:
    name: Name
    subject: Subject
    body: Body

Looking at the source code for the helper method “error_messages_for” we find the thing bothering me here:

          I18n.with_options :locale => options[:locale], :scope => [:activerecord, :errors, :template] do |locale|
            header_message = if options.include?(:header_message)
              options[:header_message]
            else
              object_name = options[:object_name].to_s.gsub('_', ' ')
              object_name = I18n.t(options[:object_name].to_s, :default => object_name, :scope => [:activerecord, :models], :count => 1)
              locale.t :header, :count => count, :model => object_name
            end

(line 199 of active_record_helper.rb)

object_name = options[:object_name].to_s.gsub('_', ' ')

?!?! They are replacing the underscores instead of doing something like:

eval(resource_name.classify).human_name

Has someone else noticed this?! And what are your fixes?
Currently I have to write the model name twice in my yaml files. This is not DRY. My file ended up looking like:

  activerecord:
    models:
      # used by EmailTemplate.human_name
      email_template: "Email template"
      # used by error_messages_for (go figure?!?)
      email template: "Email template"
    attributes:
      email_template:
        name: Name
        subject: Subject
        body: Body

Getting weeknumbers in Google Calendar

July 1, 2009

Ok I know this is a minor thing, but I would really like to have week numbers in my Google Calendar. Apparently this is not something that Google Calendar supports out of the box. We here at 41concepts use the Google App version where we use our own domain, but the following fix works for both the “normal” Google Calendar as well as the App version:

https://sites.google.com/site/gcalweeknumbers/googlecalendarweeknumbers

Generating ANT build numbers using subversion

May 8, 2009

I have been working on a Java project recently where we are using ANT as a build tool and Subversion for version control. Managing software build-versions manually is bothersome and the ANT’s build-in buildnumber task has many problems/pitfalls.

Using subversion and it’s reversion history is really the way to go for easily generating consistent, ’build’ numbers across team member machines. Furthermore, if your application has multiple modules (in multiple directories) subversion can easily provide individual version numbers for each module.

Unfortunately, subversion is poorly supported by ANT. There are many optional add-on tasks that can be downloaded, but all the ones that I looked at either did not work, was not portable or the license was unacceptable.

The best solution I could find was to invoke the subversion command line command “svnversion” directly from ANT and with a little help from here and here, I wrote a nice little macro that can be used from ANT 1.6+.

<macrodef name="svnversion" description="Get last subversion commit version.">
 <attribute name="dir"/>
 <attribute name="outputproperty"/>
 <attribute name="unversionedDefault"/>
 <sequential>
  <echo message="svnversion -n -c '@{dir}' => '@{outputproperty}'"/>
  <exec outputproperty="@{outputproperty}" executable="svnversion" failonerror="true">
  <arg line="-n -c @{dir}" />
  <redirector>
   <outputfilterchain>
   <tokenfilter>
    <replaceregex pattern="^[0-9]*:" replace="" flags="g"/>
    <replaceregex pattern="exported" replace="@{unversionedDefault}" flags="g"/>
   </tokenfilter>
   </outputfilterchain>
  </redirector>
  </exec>
  <echo message="svnversion returned '${@{outputproperty}}'"/>
 </sequential>
</macrodef>

Usage example

<!--
Sets the ant propery 'src_revision' the the subversion revision of the 'src' directory.
-->
<svnversion unversionedDefault="" dir="src" outputproperty="src_revision"/>

P.S. The last echo statement in the ANT macro also demonstrates a useful ANT trick: How to get the indirect value of a property using another property’s value as the name of the property that we are retriving the value from? This is something that is only possible in ANT 1.6 using macros.

Installing gems on passenger rails site

February 4, 2009

I just created a new server running a rails app using the wonderful Passenger plugin

After I’d install all the gems needed, I still got errors like :
“no such file to load — RMagick (MissingSourceFile)”

I tried doing a:
require ‘RMagick’

in both IRB and the console and here it loaded fine. Then I suddenly remembered the last time I installed a server (I quickly forget silly errors since it’s so easy to just google them), so I thought I’d post the solution here if I ever forgot it again.

The problem is that I’m also using the Ruby Enterprise Edition and all the gems had been installed to the “old” Ruby version. Not the Enterprise Edition. So installing the gems using the gem binary that lies under the Ruby Enterprise Edition fixed the error:

sudo /opt/ruby-enterprise-1.8.6-20090113/bin/gem install rmagick

(remember to update to the correct version)
Won’t forget that again.

Introducing Railscheck – A Q/A verification tool for Ruby On Rails

April 15, 2008

The problem

It is a law of software development that the earlier one identifies a problem the cheaper (and less embarrassing) it is to fix. Hence, we developers strive to identify errors early on our own development machines aided by sound development methodologies, tools, and tests (at best automated).

A particular quality assurance challenge with dynamic technologies like Ruby/Rails, Javascript or view templates like ERB is that you have no compiler that checks for syntax errors in advance. So you have to have 100% test coverage (which is often too expensive to be realistic) in order to be assured that even simple syntax errors does not occur.

Furthermore in the case of Ruby On Rails, which is of heavily opinionated nature, there are many conventions that can be broken by mistakes, which may introduce errors that do no show up initially. This introduces additional testing/debugging work for the programmers (in particular for newcomers to RoR).

Happily Ruby On Rails is so productive a web technology that it more then compensates for these difficulties but even though would it not be nice with some automated tool to help out a bit?

Unfortunately, your typical Ruby development tools does not provide any kind of static verification checks since the problem appears to be just about unsolvable in the general case (because of the dynamic nature of Ruby).

But what about the smaller problem of static verification checks for Ruby On Rails projects only? The RoR domain is much smaller and highly standardized so what is impossible for the entire domain of Ruby programs should be partly possible in Ruby On Rails!

Railcheck

So inspired by LINT , the power of Ruby meta-programming and various RoR testing snippets on the web, I wrote this initial beta release of Railcheck which is a semi-static verifier for your Ruby on Rails projects.

Delivered as a free Ruby gem the Railscheck project provides a shell command task “railscheck” that you can run against your Rails projects to test for a number of typical bugs and inconsistencies. See the project site and linked readme file at railscheck.rubyforge.org for details about how to install and run the tool and much more.

Railscheck is a working beta. The gem works and is useful but has a limited feature set. Much more to come. Use the rubyforge tracker function on the Railscheck website to suggest features that you would like to be added (or bugs to fix). You are also very welcome to add code/tests to the project, which is open source. Indeed the project is now open to new contributing members.

Update:

Updated the gem with improved contributor documentation, an explicit gem dependency and a fix for a typing error in railscheck.rb file. Try again if you had problems.

Rails and file uploads

April 10, 2008

While there certainly are several good file upload plugins for Ruby on Rails. It is actually somewhat hard to find any good tutorials on how to do it yourself. I just wanted to post to great links that helped me figure the whole thing out :)

http://blog.vixiom.com/2006/07/26/rails-stringio-file-upload/

http://manuals.rubyonrails.com/read/chapter/78

(Now I also know where to look when I have to work with file uploads in the future)

Ruby Fools conference in Copenhagen

April 3, 2008

So we went to the Ruby Fools conference here in Copenhagen and this post kind of sums up my experience of the different speakers. The conference went over two days and had three tracks. I primarily focused on the Advanced Rails stuff. I’ll probably update this post once you can download the presentation slides (and video).

Tuesday:

Dave Thomas explained in his opening keynote why he is a Ruby Fool :). He’s gave a great performance about his passion for Ruby and went on to compare the sudden rush of developers coming to the platform with Rails to “golddiggers and prostitutes” (before Ruby was this nice little settlement, and suddenly everyone wanted to join). That of course hit pretty much 80% of the people sitting in on the keynote. Great stuff :D.

REST: A pragmatic introduction to the Web’s architecture by Stefan Tilkov. While REST is not that new to us, and the speak therefore didn’t provide much to us, Stefan was great to talk with and I threw a few ideas on him about some of our challenges with REST (like, what do you do when you’re implementing a dashboard with some functionality also found in other places of the system – expect a new blog post on this).

Tuning the Rails stack by James Cox. Since tuning involves turning alot of knobs al over, this is not an exact science, but he did give som nice pointers on e.g. MySQL tuning and also told a few scary stories on applications that didn’t scale. On a side note, he had the coolest presentation slides (well, not really slides, I think he said it was a flash movie :))

Advanced Ruby on Rails security by Heiko Webers. I’m having my doubts on what to write here. Let me first say that the content of the presentation was great and very “german”. It was “Do this/Don’t do this”. Great stuff. No room for interpretation and once the slides are downloadable I’ll probably run through every slide while looking on our own TBA application :). Unfortunately Heiko wasn’t the great presenter and while the slides was clear, he pretty much just read them out loud, but was in trouble whenever he had to explain something that wasn’t on them.

Meta-meta programming by Nic Williams – man I love this guy.

1) The presentation was close to useless when looking at the use cases where this can be applied.
2) The subject was VERY technical

And yet… This was perhaps one of the greatest presentations due to the amount of humor and general relaxed style of Nic. Basically everyone knows meta programming, so meta-meta programming was the meta programming of meta programming. The easiest explained example in rails terms is a generator that generates generators (as I said… Not the most common use case :))

Party keynote by Evan Phoenix. A couple of sponsors had provided food and beverages so of course there was a “party keynote” (Dave Thomas wanted to swap keynote with Evan :)). While I have a great respect for Evan, the keynote was close to “not relevant at all” to me. He basically explained how he does project management on the open source project Rubinius. I’ve haven’t been in a open source project before, but what he presented was pretty much “be nice and positive to people”. There was some debate about the policy on the project that once you committed your first patch you get full commit access to the project. While it certainly works for him, I’m still having my doubts.

Wednesday

Keynote: Ruby: Past, Present and Future by Yukihiro “Matz” Matsumoto. This whas great to here it from the creator himself. There weren’t many surprises about Ruby it self, but it was great to hear about what his thoughts was on other languages and why he then went on to create Ruby. The future part was a bit cutted off because he spent a little too long bitching about character encoding (UTF-8,16,32). It was clearly something that he’s spent a lot of time on with the 1.9 release.

Versioning your data model by Ole Friis Østergaard. The presentation explained 4-5 different plugins that had something to do with versioning (also an undo redo plugin that actually looks rather nice) – including his own new plugin Subversive. I kind of noted that this was actually one of the first presentations that actually showed “real live code”.

Adding full text search to your Rails application by Jørgen Erichsen. We’re currently also implementing the search enginge Solr into our own application so this presentation was a must see. While Jørgen went through the basics of the search engine and the acts_as_solr plugin (as well as Ferret and also briefly mentioned a couple of other solutions), he didn’t seem that knowledgeable about the subject when getting to stuff outside the basic behavior of the product.

The dark art of developing plugins by James Adam. This was great. James presentation was very pedagogical buildig a plugin step by step explaining every bit of the way. While plugin development aren’t that difficult to grap, it certainly put one or two thing in place for me. I’m looking forwards to his slides so I can wrap our authorization for our application up in a plugin.

After this I unfortunely had to leave because of another engangement. So I missed one speaker as well as the ending panel discussion.

Overall the conference was well planned and executed. You could perhaps argue that it is limited what you will learn in one hour presentations, but I could just have attended the workshops leading up to the conference. As a last note… The track introductions seemed a bit off = 30 minutes break – 15 minutes track introduction – 15 minutes break (though Glenn Vanderburg was quite good.


Follow

Get every new post delivered to your Inbox.