Wednesday, September 1, 2010

Adding Your Own Hooks into Redmine



Light Background

A few weeks ago it became necessary for our needs to add my own customizations to Redmine. In particular it had to do with Repositories, but the method used can be used for anything. I used the hooks to call a combination of Perl and Shell-scripts.

Lets Get Started

This is actually really easy to do, for this example lets have our script called when a new project is created and pass in the project identifier:

First get into your Redmine root.

cd /opt/redmine

Next you need to get into the controllers so lets cd further

cd app/controllers

Now list out the files

ls

Now we want to have our script called when a new project is created. As you can probably guess this is handled in the projects_controller.rb file. First back up the file before we edit it. I am using /tmp here.

cp projects_controller.rb /tmp/

Now lets open the project controller.

vim projects_controller.rb

Scroll through the file, and notice there is a repeating pattern of def [action] sections. Naturally where it says def add (line 67 in Redmine 1.0.1 *) is where new projects get added. We just need to put our hooked call in the right place. In Ruby we call external scripts with the system command.

To add a Ruby value (the project identifier) we use Ruby's syntax. Lets say our script is /tmp/myTestHookScript.pl

We can use the following line (put it inside the add definition) to call our script (push the I key in vim to go into insert mode before typing):

system "/tmp/myTestHookScript.pl #{@project.identifier}"

If you want to get any other accessible values you can use @project.inspect to get a "dump" of the variable structure and data. Also handy is just passing values to the wall shell command to see real time event triggers when the hook is called or sending the output to a file
system "echo '#{@project.inspect}' >> /tmp/log"
and using the command
tail -f /tmp/log

to see the output in real-time. Keep in mind if you use the wall command everyone logged in can see the messages.

After making any changes you need to save and restart mongrel, do this in vim by pushing escape followed by ":wq". w- write, q -quit.

Spacing is important in Ruby, make sure you line things up.

Where Do I Get The Other Project Information?

There is probably a Ruby way to do this, but in my journeys I have been using Perl with MySQL to read from the Redmine database, and get the needed information using things like the project identifier passed into my scripts to figure out what information to grab.

* To turn on line numbers in vim type escape followed by :set number (you need to type the colon) and then push enter


No comments:

Post a Comment