Title Image
Twitter Logo
http://tiny.cc/cznl3 gotta love Harry. 5 days ago
Follow me on twitter @stewartmatheson

Introducing assert-random

3rd
8 / 2010

Something I have been meaning to do for a long time now is create and release a ruby gem. Today I have done this. Introducing assert-random. Its a VERY simple gem that adds an assertion to test/unit. Assert random as a test accepts a block and runs this block 10 times. Once the block has been run it then checks the results of the block. Currently it tests to make sure that no objects that are the result of the block match. Not much but its a start.

Example that passes:

1
2
3
assert_random do
    rand(1000)
end

Example that fails:

1
2
3
assert_random do
    1000
end

Basic stuff but I plan to extend it in the future so something like this will fail:

1
2
3
4
counter = 1
assert_random do
    counter += 1
end

I used the gem Jeweler. I got up and running very quickly and was able to focus on the functionality of the gem and not all of the meta details a gem needs. All that was generated for me. Awesome really.

Source: http://github.com/stewartmatheson/assert-random
RubyGem: http://rubygems.org/gems/assert-random

Using Ruby, require, include and Mixins

20th
7 / 2010

When I first discovered Rails all those years ago I had not really heard of ruby. I think rails introduced a lot of new people to ruby such as my self. Its great for ruby to have all these new users however this is a problem as well. The problem is that people such as myself jump right in to rails with out fully understanding ruby or in my case even partly understanding ruby. This in it’s self is not a probelm however the deeper you go in to rails the longer your going to have to go back and look at the naked ruby. This can lead to some problems later down the line. It can also make other peoples code hard to read. This is a weakness and something that I have been working on skilling up on.

This weakness was exposed today when I was trying to write an acts_as_method. I am currently working on a rule based AI system and I wanted to separate the underlying code of the AI system from the rails models that provide the knowledge. Thats where the acts_as_method comes in. However it came in rather slowly.

My first hurdle was looking at the require vs include. Both sound the same but do different things. Its important to understand this. The require opens reads and evaluates the code with in a ruby file. So for example say I have a file called Person.rb. In this file there was a class called “Person”. With me so far? I am working out of a file next to Person.rb called test.rb. Test.rb needs to know about Person.rb so that the Person class can be used. To do this we simply use

require 'Person.rb'

Simple enough. Ruby also supports shortcuts and will auto append the .rb so

require 'Person'

will also work. Again simple enough however all of a sudden it looks like we are talking about a class or a module here. This is what threw me a bit at first but remember it is the file. Directories work as you would expect. Say our person.rb is now in a models directory. Just use

require 'models/person'

Again no .rb but remember it is the file we are talking about. That brings us to include. Include in c++ for example includes a file the the way require works as described above but this is not the case in ruby.

In ruby we have mixins that allow use to add a module full of methods to any class we like. This is great and very handy as ruby does not support multiple inheritance. But who cares. Mixins are simple to use and make more sense. So lets consider the following

class Person
  def say_goodbye
    "goodbye"
  end
end
 
module PersonMethods
  def say_hello
    "hello"
  end
end
 
Person.include(PersonMethods)

Here we have a person class. We have a module with a method and we are using the include method to add the module methods to the person class. Now the person class will have both the say hello and say goodbye methods. The include is working on the program level. Not the file level. Very different to #include in c++ for example. I think form memory PHP has something smilier.

Who cares? Why do I need to do this? Why not just put both methods in the person class. Well you could do that and in this case its fine. However think about developing a Rails application for example.  You might have some logic that you want to use in a number of Rails applications. Cuting and pasting code from one model to another is one way to it but what about the following?

ActiveRecord::Base.send :include, PersonMethods

This is one of my favorite things about ruby. You can add in methods to classes that have already been declared else where.  You can add them when you need and you can break up your methods in different ways and add them at different times. All of a sudden your writing extra features in to rails with out even touching the source. Well the rails models at least.

This does not just stop at rails. You can apply this to any class anywhere. You can even apply it to core ruby classes. You can change the way ruby works at runtime! Check out the ruby homepage for lots more info.

Events in ActionScript3

14th
7 / 2010

There are a lot of posts around the Internet on ActionScript. A lot of them are very poorly written. Whilst they take the time to explain the “what” they don’t take the time to explain the “why”. I will attempt to do that with this blog post.

Events are a vital part of developing with ActionScript 3. Events are a very flexible way to make your code moduler and loosely coupled. Flush supports a number of events prepackaged. These include mouseclick events and keyboard events.

Whilst these are important for making any kind of user interface its custom events can I am going to explain how to use today. In the example I set up custom event for a unit within a strategy game I am developing. Think of civilisation and moving units around on a map.

When creating a custom event the first thing to do is write the custom event class. The custom event class must extend the event class which can be found in the flash.events package.

In this example the unit event class covers all events that relate to units. Obviously. Specifically the events I wish to send include movement, when the unit is selected, when the unit is deselected and when the unit has finished its movement.

In the class there is a static string declared representing each of these event types. The event model in action script uses this string to decide what listeners to call. Therefore this string is needed when adding an event listener.

In the class is the constructor. The constructor accepts one variable which is this event string. Make sure when you declare the constructor that the super call with the command string is present. This is all ActionScript needs to handle the event.

You may require to send additional information with the event. I have done this by using get and set methods. As the event is simply a class there are no limits on what functionality you can implement within the event itself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.events {
 
	import flash.events.Event
	import com.geom.MapPoint;
 
	public class UnitEvent extends Event {
		public static const MOVEMENT:String = "movement";
		public static const SELECTED:String = "selected";
		public static const DESELECTED:String = "deselected";
		public static const MOVEMENT_COMPLETE:String = "movement_complete";
		private var targetLocation:MapPoint;
		private var startLocation:MapPoint;
		public function UnitEvent(command:String) { super(command); }
		public function getTargetLocation():MapPoint { return targetLocation; }
		public function setTargetLocation(t:MapPoint):void { targetLocation = t; }
		public function getStartLocation():MapPoint { return startLocation; }
		public function setStartLocation(t:MapPoint):void { startLocation = t; }
	}
}

Once we have the event class written we a free to dispatch it. Despatching an event can be done from any class that extends IDispatcher. IDispatcher is built into ActionScript.

The following example is an excert from a class that handles the unit. The code creates a new unit event. The new unit event takes one constructor which is the movement complete static variable of the event itself. This calls any listeners that are subscribed to that particular event type. After the locations are set the dispatchEvent method is called. This takes one parameter which is the event instance.

1
2
3
4
5
6
7
8
9
if(movesLeftThisTurn <= 0)
{
	var movementCompleteEvent:UnitEvent = new UnitEvent(UnitEvent.MOVEMENT_COMPLETE);
	movementCompleteEvent.setStartLocation(startLocation);
	movementCompleteEvent.setTargetLocation(currentLocation);
	startLocation = m;
	movesLeftThisTurn = movement;
	dispatchEvent(movementCompleteEvent);
}

So now we have a custom event class, we have code that dispatches the event however we do not have any way of listening for the event. A listener is set up with an addEventListener method. This method takes two parameters.

The first parameter is the string representation of the event. Remember when we first created the instance of the event? We passed it a single string parameter. When we add an event listener that listener will only be called if the event is created with that particular string parameter. This allows us to create different types of events in a single class. It also allows us to blind behaviours for different events. A very powerful system!

The second parameter that this method takes is a string representation of the function that the event is calling. Make sure to omit the brackets at the end of the function as we dont want to call function we simply want to tell the listener about it.

1
2
3
4
5
6
7
function unitFactory():Unit
{
	var u:Unit = new Unit():
	u.addEventListener(UnitEvent.MOVEMENT, unitView.moved);
	u.addEventListener(UnitEvent.MOVEMENT, activeState.selectNextUnit);
	return u;
}

The final step is to add the actual listener. The listener is a function in itself. The listener accepts one variable. The event that you have passed. This was the event that was sent in the dispatchEvent method. Make sure that every event listener returns void. If the event listener does not have a return type void then the event will not be fired properly.

1
2
3
4
5
6
7
8
class UnitView extends View {
	...
	public function moved(e:UnitEvent):void
	{
		x  = e.getTargetLocation().xpos;
		y  = e.getTargetLocation().ypos;
	}
}

In the above event listener we update the units position as this event listener is fired when the unit is moved.

I hope this helps. Please give me feedback. If there is any other topics you would like me to blog about please don’t hesitate to ask.

Tutorial: Installing Nginx, Apache and SVN

7th
4 / 2010

In this video I install Nginx Apache and SVN. Download links are here…

http://mirror.lividpenguin.com/pub/apache/httpd/httpd-2.2.15.tar.gz

http://subversion.tigris.org/downloads/subversion-1.6.9.tar.gz

http://nginx.org/download/nginx-0.7.65.tar.gz

Here are the apache configurations I used

<IfModule mpm_prefork_module>
    StartServers          1
    MinSpareServers       1
    MaxSpareServers       1
    MaxClients           10
    MaxRequestsPerChild   0
</IfModule>
 
<Location /repos>
    DAV svn
    SVNPath /usr/local/nginx_svn_test/testrepos
    SVNAutoversioning on
    Options Indexes FollowSymLinks
    Order allow,deny
    Allow from all
</Location>

This is the Nginx proxy pass configuration

location / {
  proxy_pass http://localhost:86;
}

The following is the line that configures the apache compile.

./configure --enable-dav --enable-dav-fs --prefix=/usr/local/nginx_svn_test --disable-alias --disable-userdir --disable-actions --disable-dir --disable-negotiation --disable-cgi --disable-cgid --disable-status      --disable-autoindex --disable-asis --disable-mime --disable-version --disable-setenvif --disable-env --disable-log-config --disable-include --disable-filter --disable-auth-basic --disable-authz-default --disable-authz-user --disable-authz-groupfile --disable-authz-host --disable-authn-default --disable-authn-file

The following is the configure line for the SVN install.

./configure --prefix=/usr/local/nginx_apache_svn_test --with-apxs=/usr/local/nginx_apache_svn_test/bin/apxs

Working on the subject observer pattern

23rd
3 / 2010

Lately I have been writing a lot of game oriented C++ code. As with any form of development it’s both a rewarding and frustrating process. I am relatively new to C++ as well so I am still grappling with the ins and outs of the language.

One of the things I have come to love about C++ is the flexibility. You can code C++ in virtually any style you want. It supports a higher level object oriented design but you can also get down and fiddle with bits if you need to. At the moment I’m interested in the high-level features of the language, the low-level features can wait.

One thing I have been working a lot on is the understanding of programming patterns in relation to C++. For the kind of work I am doing at the moment understanding programming patterns is almost as important as understanding the language itself. You can code in an ad-hoc way however it’s when you start to introduce programming patterns when things start to make sense and become… dare I say fun. Just look at the impact Ruby on Rails had to the Web development world. In a sea of ad hoc development one framework comes along that implements one gigantic programming pattern and it’s hailed as the second coming of Christ.

One of the most important programming patterns is the subject observer pattern. This is what I am detailing in the post. Subject observer fits in with model view controller. Basically a change to the model occurs, the model notifies the views on the subject and the pattern is born. In this particular example the subject is the model and the Observer are the views. It doesn’t have to be particular to any other class and the example I give allows you to inherit from the subject observer classes and implement them in any way you want. One of the goals with this exercise was to keep the solution is generic as possible.

The subject observer pattern is powerful because it allows you to loosely couple your views and your models. Who doesn’t love that. In C++ terms the model contains a vector pointers to its observers. The model is dumb in this sense. It doesn’t know who its observers are and nor does it care. Observers can be added and removed from the model at any time as long as some sort of a array/vector/list of the observers is maintained. Note that this “model” solution does not include away to detach subjects from observers. It should not be too difficult to work this out but if you have problems ask me.

The following example has been tested with the GNU C++ compiler. In this case I am running it on a Macintosh. The code should be fairly generic and you should be run at different compilers. If you can’t let me know.

In the code the horn class observes the alarm class. Thus making the alarm class the subject. Note how the horn and alarm class inherit from observer and subject respectively. The alarm gets triggered by the yes you guessed it triggered method. This it is an update to the model and as a result calls the notify observer method. This method which is inherited from subject loops through a vector of observer pointers calling the notify method on each observer. The notify method is a member of observer and inherited in the Horn class. The notify method gets passed a subject. This is so the notified object can extract information from the subject. While some solutions may not require the notified object to obtain any data from the subject the solution allows the Observer complete access to the subject.

Note in the horn class that there is a typecast. This typecast converts the subject pointer and alarm pointer allowing methods on the alarm to be called from the Horn class. In this case the Horn class fetches the ID of the alarm but it could be any kind of data.

I hope this explanation of the subject observer pattern helps. If you have any questions please post a reply to this comment. I will try to answer questions to the best of my knowledge bearing in mind that I am new to C++ myself.

Anyway time for code.

#include <vector>
#include <typeinfo>
#include <string>
 
class Subject;
 
class Observer
{
public:
    virtual void notify(Subject* s) = 0;
    virtual ~Observer() {};
};
 
class Subject
{
    std::vector observers;
protected:
    void notify_observers()
    {
        std::vector::iterator iter;
        for (iter = observers.begin(); iter != observers.end(); ++iter)
            (*iter)->notify(this);
    }
 
public:
    virtual ~Subject() {};
    void register_observer(Observer* o)
    {
        observers.push_back(o);
    }
};
 
class Alarm : public Subject
{
public:
    Alarm()
    {
        std::cout << "alarm created" << "\n";
    }
 
    void triggerd()
    {
        std::cout << "The alarm has been triggerd" << "\n";
        notify_observers();
    }
 
    int const get_alarm_id(){ return 100; }
};
 
class Horn : public Observer
{
public:
    virtual void notify(Subject* s)
    {
        Alarm *a;
        a = dynamic_cast<Alarm*>(s);
        std::cout << a->get_alarm_id() << "\n";
    }
};
 
int main ()
{
    Alarm a = Alarm();
    Horn h = Horn();
    a.register_observer(&h);
    a.triggerd();
    return 0;
}

Dividing numbers in Ruby

15th
10 / 2009

Today like other days I was working on a game in ruby. Like any game this game uses a lot of rand(). Writing code for this game I came across this little quirk/feature of ruby. When dividing two integers ruby will return an integer. EG…

>> 10 / 2
=> 5

Thats fine but what about the following…

>> 100 / 56
=> 1

Ruby in this case did not return a float like I expected. It returned a rounded integer. To get a float make sure your dividing two floats.

>> 100.to_f / 56.to_f
=> 1.78571428571429

Thats more what I expected. So maybe you already worked this out but it was a slight trip up for me.

Uniform Forms in Rails

5th
8 / 2009

In my travels as a Rails developer I write or rather generate a lot of forms.  In most web applications I build it’s desirable to have forms that look uniform across the entire application. I have been working on apps where I wish I had one place to change the out put of all forms.  To solve this problem I wrote a helper that renders a partial and outputs one form look for the entire app. First lets look at the code in the view of the form

  <% label = f.label :email %>
  <% element = f.text_field :email %>
  <% help = 'Please enter a valid email address' %>
  <%= form_element label, element, help %>

Here we are in side a form_for block. This is the standard form_for block rails scaffolding builds for us. I am setting both the label and the form element and passing it to values. I suspect there is a better way to do this with blocks. If there is please reply to my post and let me know.

Next lets look at the form_element method.

  def form_element(label, field, help)
    return render :partial => 'shared/form_element', :locals => { :label => label, :field => field, :help => help }
  end

Basically renders a partial and passes all the values to it. Here is the partial

<p class="form_paragraph">
	<div class="label_container">
		<%= label %>
	</div>
 
	<div class="form_element">
		<%= field %> 
	</div>
 
	<div class="form_help">
		<%= help %>
	</div>
 
</p>

Done.

Loading a single fixture in rails.

14th
7 / 2009

UPDATE:
At the time of this posting I did not know that there was already a way to do this in rails but thanks to Robert Siemieniec for letting me know.

rake db:fixtures:load FIXTURES=name_of_fix_file,name_of_other_fix_file

So just use this in the future. My solution still works if you wanted to have a separate rake task. However honestly there is no point just go with what rails has out of the box. If you really want to have your own rake task then read on.

After launching Would u prefer I was amazed how quickly spam started appearing on the site. Would u prefer is a social site that encourages casual users to post with out them being required to sign up. While this makes the barrier to enter this site it does open doors for spam bots. So I added a challenge system to non-signed in posters. Answer a simple question and the post will be allowed. Fail to do so and the post will not work. Simple. Well the implementation in the rials app was however I did hit one snag.

How would I load the challenge questions in to the database on the production server? I like rails fixtures so I created one for the questions. However there is no way to add fixtures in rails one by one and I found that blank fixtures in some of my other models where overriding the existing database. As I don’t need all my fixtures (only the one with the rails questions) I wrote a rake task that will load a single fixture.

namespace :db do
  namespace :fixtures do
    desc "Load a single fixture by setting FIXTURE=name of fixture you wish to laod."
    task :load_single => :environment do
      require 'active_record/fixtures'
      ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations[RAILS_ENV])
      Fixtures.create_fixtures("test/fixtures", [ENV['FIXTURE']])
      puts "Fixture #{ENV['FIXTURE']} loaded in to #{RAILS_ENV} environment."
    end
  end
end

Usage…

rake db:fixtures:load_single FIXTURE=questions

Where questions is the file name of the fixture you wish to load.

Some might think it better to add this within a migration. That’s a fair call as well but I am not sure of any migration methods that are there to load fixtures. If there are let me know. I suppose a plugin would be the next step here but this quick and dirty task solves the immediate problem.

+1 to mod_rails

15th
6 / 2009

Today I finally updated to mod_rails. The install was easy. I was missing a few requirements however the install process told me in exact terms what I needed to do. After rerunning the install everything worked. The mod_rails install process seemed almost too easy.

For those not in the know mod_rails handles everything you need to bring your rails app to production. All you have to do now is plonk your app on a server set up the database. Mod_rails does the rest. Mod_rails also removes the need for a mongrel cluster thus reducing the amount of memory used by the server. Very handy for users such as my self running on small hosting slices. The configuration is also much easier. I reduced a 36 line configuration file down to 4 lines. The only regret I have about mod_rails is that it renders my post on setting up a mongrel cluster with proxy balancer useless. Mod_rails … it just works. That is all.

Check out mod_rails when you get a chance.

Adding tabbed navigation with a helper method using rails.

9th
6 / 2009

I am currently building an app that has a tabbed interface. To my surprise I realized that I have never had to code a tabbed application before. I wanted an easy way to add tabs to my rails application. I used a helper method to identify what the currently selected tab is and add an active class to it.

  def link_with_active(text, url)
    link = link_to text, url
    if request.request_uri == url
      return '<li class="active">' + link + '</li>'
    else
      return '<li>' + link + '</li>'
    end
  end

Basically this method is an if statement that adds the active class to the li item. Since I would almost always build a tabbed list with an li I thought it was a safe assumption to build this in to the method. Then I just call the helper method from my view. Like so.

<ul>
	<%= link_with_active "Home", "/" %>
	<%= link_with_active "New Invoice", new_invoice_path %>
</ul>

To be honest I am not totally sure if this is the best way to do this. If anyone has a better way of doing so please comment.

Older Posts »