You are here: Blogsphere Longtail
Keep up to date with your favourite Rails bloggers in context.
@xentek Another SVN client for…
Refactoring an ActiveRecord callback
Inspired by a few articles and pesentations (1 2 3 4), I decided it was time to cleanup some of the logic in my Post model related to a particular ActiveRecord callback. The fact that I needed some comments to explain what it is doing should be a red flag.
before_validation :update_published_at_if_necessary
def published?
self.is_published == true
end
def unpublished?
! published?
end
protected
# Ensure that published_at is set accordingly.
#
# * Unpublished posts should not have this set
# * Published posts should have it set to the current time
def update_published_at_if_necessary
if new_record? && published? && published_at.nil?
self.published_at = Time.now
end
if ! published? && !published_at.nil?
self.published_at = nil
end
end
Fortunately, I have tests in place that excercise this logic, so as long as my tests are passing, the refactorings must work (hopefully!).
My first impression is that the callback is doing too much work. Let's split it up into two pieces.
before_validation :set_published_at_to_now_if_necessary
before_validation :unset_published_at_if_necessary
protected
def set_published_at_to_now_if_necessary
if new_record? && published? && published_at.nil?
self.published_at = Time.now
end
end
def unset_published_at_if_necessary
if ! published? && !published_at.nil?
self.published_at = nil
end
end
That's somewhat better. At least the methods are more focused.
Hmm, I probably don't need to check the existing published_at value when something isn't published. I can also make use of unpublished?
def unset_published_at_if_necessary
if unpublished?
self.published_at = nil
end
end
I would do something similar for set_published_at_if_necessary, but I don't want to override the published_at if it was explicitly set. Maybe I post something in the future, or past. I go a little crazy sometimes with that.
I could probably simplify the conditional logic in set_published_at_if_necessary by making a new method.
protected
def set_published_at_to_now_if_necessary
if new_published_post_without_published_at?
self.published_at = Time.now
end
end
def new_published_post_without_published_at?
new_record? && published? && published_at.nil?
end
Having if_necessary into the method names are kind of bugging me. before_filter supports :if and :unless options, so we should use those, and remove the conditionals from the callback methods.
before_validation :set_published_at_to_now, :if => :new_published_post_without_published_at?
before_validation :unset_published_at, :if => :unpublished?
protected
def set_published_at_to_now
self.published_at = Time.now
end
def unset_published_at
self.published_at = nil
end
Looking good. Looking pretty, pretty good.
Let's see the finished product:
before_validation :set_published_at_to_now, :if => :new_published_post_without_published_at?
before_validation :unset_published_at, :if => :unpublished?
def published?
self.is_published == true
end
def unpublished?
! published?
end
protected
def set_published_at_to_now
self.published_at = Time.now
end
def unset_published_at
self.published_at = nil
end
def new_published_post_without_published_at?
new_record? && published? && published_at.nil?
end
I'm pretty happy with this. Reads really well. Some of the methods have kind of long names, but I can deal with that.
The only part I don't really like is published? and unpublished?, but that's for another day.
This September, I’ll be presenting at RailsConf Europe on EC2, MapReduce, and Distributed Processing. The talk will explain the MapReduce approach to distributed processing, will show a few example implementations, and will discuss MapReduce vs. other distributed processing techniques.
Whether you’ll be there or not, if you’re interested in learning more about MapReduce, here are some resources. I’ll write a few more posts on the subject before the conference, so watch this space as well.
Cluster Computing and MapReduce is a great series of video lectures given to Google interns in 2007. The first two are the most appropriate: the first introduces distributed processing concept, while the second covers MapReduce itself.
MapReduce: Simplified Data Processing on Large Clusters is the paper by Jeffrey Dean and Sanjay Ghemawat of Google that got things going in the first place.
MapReduce for Ruby: Ridiculously Easy Distributed Programming discusses MapReduce and introduces Starfish, a Ruby library for distributed processing. Starfish is not a MapReduce implementation, however – it takes a somewhat different approach to distributed processing.
Skynet (a few writeups: InfoQ, Dion Almaer) is another Ruby-based distributed processing system inspired by MapReduce.
Writing Ruby Map-Reduce programs for Hadoop discusses using Ruby to wrap Hadoop, a MapReduce-like system built in Java.
Introduction to Parallel Programming and MapReduce at Google Code University, a good overview of distributed processing and the MapReduce approach.
And finally, one article that you should avoid:
MapReduce: A major step backwards compares MapReduce to relational databases, and says that MapReduces loses out because it doesn’t support database indices, database views, Crystal reports, etc. Basically, the complaint is that MapReduce isn’t SQL compliant. WTF? Clearly, the author(s) didn’t understand what MapReduce is. The problem, as explained elsewhere, is that the authors thought that MapReduce == CouchDB/SimpleDB. Which is obviously not true. %s/MapReduce/SimpleDB the original article and it makes some sense. But long story short, this article will teach you nothing about MapReduce, and will likely confuse you further. So stay away.
Cattle Brands

During my road trip across the United States we took a short rest
somewhere in the middle of Montana and I saw this interesting display
of local cattle brands.
My favorite is the “Lazy P Swinging 9”. I think I see the beginings of
the Weezer =W= in there too!
SproutCore - a javascript framework
A post at Coding Horror got me thinking how the experience of using regular expressions through out code can be improved. I use them frequently in various cases, but many programmers though about them being like some kind of super-human ability:
The syntax of regular expressions itself isn’t very welcoming and some (really) ugly examples can be found on the web. Also, the creation of a single expression can be a bit long and error prone process, even for experienced programmers and testing their correctness isn’t painless either. What options do we have then?
Well for creating my own regular expression, I often fall back to a external tool. I use an online tester: Rubular. Although it’s said to be for the ruby language, the rules and characters are pretty generic for most regular expression engines. After getting the expression right on Rubular, I just integrate them with my code. Most of the times I just abstract it to its own method, to help with code reuse and testing. The pocket reference that I acquired also comes in hand, with all the rules explained and implementations for all the popular languages.
Unfortunately there isn’t much intellisense for regular expression when it comes to IDEs. Here I’m talking about identifying them (an easier task in some languages like ruby and perl, in which they have been granted with a unique syntax), checking if the syntax is valid, automatically offer a box where you can throw several test cases, and other nice features you can probably think of.
Finally, some experiences have been done towards making the regular expression a bit more programmer friendly. Most notably, a readable version through object-oriented rendering of the regular expression string. A random example of what it looks like:
Pattern.With.Literal(@"<div")
.WhiteSpace.Repeat.ZeroOrMore
.Literal(@"class=""game""").WhiteSpace.Repeat.ZeroOrMore.Literal(@"id=""")
.NamedGroup("gameId", Pattern.With.Digit.Repeat.OneOrMore)
.Literal(@"-game""")...
It’s arguable if this version is itself a improvement not only in readability, but also in maintainability (bigger number of lines for example). A lot of arguments have been thrown at the coding horror post comments section, so I suggest you read a bit through them. In my personal opinion I found the syntax a bit harder to remember and would only increase the overhead of making casual changes. However, I also agree that for some folks it might be a simpler and familiar way to start using regular expressions, specially if they’re all against learning a new language.
This morning we had a meeting with a potential new client. When he asked us to name the companies we’ve worked for recently, I realized we haven’t posted much about the work we’ve done in the last year or so.
Mostly, we’ve been working on larger back-end and some internal projects. We helped Brighter Planet build a web application that allows people to keep track of, and then reduce, their climate impact. They’re now up and running, and slowly moving their Rails development inside the company (they’re hiring).
For Prada we built an auction system which has been used to sell unique prototype pieces. This project is now also being maintained by an internal developer at Prada.
Boom Test Uitgevers, a publisher of psychological tests, asked us to design and implement an architecture that allows third-party developers to integrate Boom’s tests safely and easily. We decided to split their existing Rails project into a separate account management and multiple test scoring applications that talk to eachother using ActiveResource. See the Account Manager and Scoring API documentation for an overview of how this works.
For another tests publisher, Bohn Stafleu van Loghun, we designed and implemented three different testing products, one providing diagnostic tests for psychotherapists, one that allows teachers to screen schoolchildren for psychosocial problems, and an early warning instrument for use in eldercare.



We also created two e-learning applications; Dr.Stat, a statistics course developed by the University of Amsterdam, …


…and Basics, currently being used by the educational publisher Boom Onderwijs to create various courses.


For Mountain Goat Software we designed and built Planning Poker, a fun estimation tool for distributed agile teams.

Finally, we also did a few regular website projects, for example Rijnboutt Van der Vossen Rijnboutt, Hendriks Schulten architecten, and Uitgeverij Luister.



Well Micah tagged me, and if I look at these XML request/responses for another hour without a break I’m going to pass out into my keyboard. Here goes.
I had a Texas Instruments computer thingy that I got for my 6th or 7th birthday, somewhere in there. It played these educational games, but I noticed one day that if I didn’t put a cartridge in it a blue screen came up with a cursor. It had an instruction book and I would basically type in the programs verbatim, then do little things with it like change a color or a line. Later I had an Atari XE and it did the same thing, so I made the same little guessing game in it just like the one I made on the TI. Realistically I didn’t write anything of use until high school though.
Interestingly, perhaps only to me, my version of Hello World for the iPhone SDK was a guessing game.
I guess that was the real answer. I played with my dad’s computers all the time but didn’t consider it as a career until I was about 16 or 17, when I realized I could probably get paid for it. Up until then I wanted to be a sports journalist. So I went to school so I could found my own game company.
What counts as “real”? The guessing game? Making horizontal lines appear on the screen? I wrote a bunch in Basic and Pascal for homework assignments, and like Micah had one of those TI calculators. The first specific one I can recall was a text-based adventure game I made for a homework assignment my freshman year. It was based on the Haymarket Bombing
Pascal, C, C++, C#, COBOL, Assembly, Perl (but I won’t admit it), Java, Objective-C, Ruby, Javascript, Lisp, VB, Erlang, and I just wrote Hello World in Smalltalk (Squeak).
I too doubt I could write Hello World in most of those languages, and wouldn’t put them all on my resume. It’s funny because I probably would have when I came out of school, since I didn’t know the difference between “familiar with” and “able to write some code with”.
I started a web design company in college, which employed me and myself. I had two clients, one of whom paid me in Kung Fu lessons.
Find great people to work with. If you’re the smartest person in the room, you need a new room, because if you’re not growing you’re dying. This is tricky when you’re new, since you don’t know a great developer from a tree stump, but take a look at Micah’s tag list. It looks like the list of authors in my library.
I would also tell them they should come to work for me as my apprentice, unless they weren’t any good. Then they can work for Jim.
Working with the team I work with now is fantastic. I also had a great time working Agile 2007 as part of RailsFest, and I’m looking forward to doing the same thing on the Live Aid stage this year.
Sadly I don’t know many developer’s who keep blogs, so I’ll just echo Micah’s list and tell Paul, Jim, Doug and Matt they’re next.
trms goal week wrapup
Hack to fix "undefined method" error when running rake on a gem not yet installed
Recently, while trying to install the ultrasphinx gem for one of our projects, I ran into this little bonus:
(in /Users/cblackburn/Source/ruby/bols)
These gems that this application depends on are missing:
- ultrasphinx
Run "rake gems:install" to install them.
rake aborted!
undefined method `validates_email_address' for #<Class:0x1f577f0>
/Users/cblackburn/Source/ruby/bols/rakefile:11
(See full trace by running task with --trace)As usual I won’t bore you with why it happens other than to say the loader doesn’t work properly in this instance. To hack around it find out which models are using the ‘undefined method’ and place the following inside the class definition, before using the method.
# Hack to fix "undefined method" error when running rake on a gem not yet installed
require File.join(RAILS_ROOT, 'config', 'initializers', 'custom_validations')Comment if you need more help or if this is not clear.
You can have the life you want.
Saved By: Rich Orris | View Details | Give Thanks
Tags: photography, unrulythings
"Their version of our mission is to go [on a course] for umpty-x thousands of dollars, so they can..."
Their version of our mission is to go [on a course] for umpty-x thousands of dollars, so they can claim they were “certified”. One two-day blowjob and they’re set for life. Sure, it tastes like salted raw egg-whites, but afterwards you’re *Agile*.
Kids. “Agile” is for people who don’t have the balls for “XP”. I’m sorry to be the one to tell you, but lookit, agile always was a word provided by marketeers, bereft of any commitment beyond what could be sold. It always fucking was.
”Vandaag heb ik gebotst. Boem met mijne mooie auto. Den eerste keer ooit, in ik weet hoeveel jaar, +10. Ik was/ben onder den indruk. Daar moet ge dan eerst +3000 km voor rijden om dan achter den hoek (bij wijze van spreken) te botsen.
Gelukkig enkel materiele schade. En ook dat valt nog mee.
Desalniettemin niet plezant.
On the 1st July 2008 the SLK Course Manager package was uploaded to codeplex, this was something that I had been waiting for as there are plans to incorporate functionality into a project I am currently working on. Having installed and tested the solution I can say that I am totally under-whelmed, this add-on was expected to fill the Gap left after the move from Class Server to SLK/MLG.
Please feel free to grab the download an try it out for yourselves, and post comments if you think I have this wrong.
A brief review of the Installation Guide highlighted some real concerns
For most these two statement alone should have started alarm bells ringing, and you are going to be pretty brave to let this code out to on you live installation. Others have been waiting for ages for these additions so will press on.
The installation process is not too bad, you do need to pass in a parameter for the URL that actually has a web site - not a problem for most but if you have been a good SharePoint person and spilt out you schools into site collections you may not have a site at the root.
Central Admin feature activation is ok but I would have liked this to have been automated. Database creation is a bit light - it works but could have been more helpful in pulling in default database details and suggesting a name, the code for this is already in SLK so a bit lazy that!.
Only one database? It appears that the solution relies on a DB connection setting in the registry, meaning you can only have one database for course manager across the entire farm. This may be ok for single school installations but what about the managed services or District (Local Authority in the UK) deployments. Again why not use the same approach adopted by SLK to keep things consistent.
Activation of the Course Manager on a site is all a bit too manual. Considering you would need to do this as a site for each and every course.
The instructions do guide you through this feature activation and adding the 3 web parts so i'll just look at these.
Course Manager Pages Web Part, just provides two links to the Plan and Assign page and the Monitor and Assess page (both stored in as forms in a document library). I'm not sure of the design reasons for using a document library to hold pages and then not display the pages, also why the link on the Quick Launch when you don't use the library?
The web part does not appear to have any logic, i.e. if I log in as a student I still see both links? why not hide them if you not an Instructor or Admin?
As described above this page is stored in the forms library of the Course Manager Pages library. But you have to manually add the Plan and Assign web part. Come on please this is not hard to automate a page with some web parts on it!
In this page you have the ability to group assignments into Activities (in fact assignments as used in SLK are called activities in Course Manager) so you have Activity Groups which can have multiple Activities. This is fairly useful in that it allows you to organise activities together. The UI has made use of Ajax so no need for page postbacks - whilst I agree with this I find the actual UI to be very unfriendly.. Why do I click on a blue bar (that looks like a toolbar) in order to show a text box for data entry?
The file upload is good, you can upload a document without leaving the page, but it's very limited. Why can it only use one Library? What if you have course material stored centrally do you have to copy it here? it appears so with Course Manager. Also if you navigate Up from the root of the document library you get completely redirected away from the page.
Assign / Unassign is an all or nothing activity, no way to choose which students to assign the work to as in SLK, this is an all students regardless! Not sure if that really reflects the real world where you will have mixed ability students in the same class.
I also noticed that any work you have assigned via SLK directly can only be viewed here - no ability to manage these or group into activities.
As with the Plan and Assign page you have to manually add the web part which as you can see below is not really the GradeBook we were expecting.
Without any documented instructions this screen is just difficult to understand. There are options to enter values on this page, you can Save - but what? Return to learners - what am I returning? Here we actually see the first real reference to a Course - pretty lame considering this is supposed to be a Course Manager.
Clicking on the Activities (assignments) takes you to the normal SLK assignment management screens.
And that's all that I could find?
At this point your probably looking at the documentation to see what was missed! If you find anything please email as I've not found anything yet. After installation you move straight to Uninstalling! Wait perhaps that's what is going to happen in reality once people see how little you get from the add on.
Disappointment in what has been provided has been raised and I am hoping that in the next few days I can report that I missed a whole area of functionality, but having looked at the solution files and code (I know it's not available, but Reflector does a great job :) ) I can't see anything.
Oh and I nearly forgot, if your upgrading from a previous version there is a database Schema change (still testing the MLG version) as the new Observer role has been introduced. Looking at the SLK documentation you are advised that in order to upgrade you need to delete you SLK database and create a new one.
Yes you read that correctly... DELETE YOUR DATABASE!!!
So all that work that you have done so far with SLK will. ummm be lost??? This for me is just ridiculous, how about running something like SQL Compare on the DBs and a little bit of code to perform the upgrade, I mean if we can upgrade SharePoint databases from V2 to V3 this should be a walk in the park.
Mais Text Munger
Whitespace, punctuation, numbers -- anything that isn't a word -- should also remain unchanged.
Ou seja, minha implementação anterior está fundamentalmente errada 
E eu só li essa parte do enunciado depois do comentário do Rodolpho.
Mas é fácil de resolver, usando o shlex mesmo:
Ya sé que muchos pensáis que tenéis otro órgano mucho más maravillos, pero hoy va sobre el cerebro. He aquí la cita:
El cerebro es un órgano maravilloso. Se pone a trabajar al levantarnos y no deja de funcionar hasta entrar en la oficina.
Robert Frost (Poeta estadounidense)
(Sacado de Espai Multimèdia)
Espero que no leáis mi blog en la oficina, sino ahora puedo explicarme algún que otro comentario descerebrado que deja la gente.
Con la de tacos que ha puesto supongo que mi posicionamiento web habrá mejorado para búsquedas guarrillas. Gracias majo.

Sí, este hombre es Robert Frost, ¿quién lo diría verdad? Tiene cara de Robert, pero no de Frost.
이 글은 꽃띠앙님의 2008년 7월 3일의 미투데이 내용입니다.
<!-- end of daily_digest -->
Unit Testing iPhone apps with Ruby: rbiphonetest
Hot Dog! Reserve price met on my ipod touch. We’re going to make a sale!
I haven’t kept up with the Blender community for a while,...

Nashville Scene - Meet Caldwell Hancock
ACLU v. US Constitution
thoughts on a more generic Array#partition function - ruby-talk-google | Google Groups
"If there is a day in law schol when students learn not to refer to an opposing counsel as..."
Tell us what you think of the new BlogSphere feature. We are continually looking to improve and update the
functionality based on your feedback.

Find your next Ruby on Rails project or job.
Exclusive content,
regularly updated - onsite and tele-working positions listed.
My go-to man for rails questions.
-
J.Z, United States