You are here: Blogsphere Longtail

Rails BlogSphere

BlogSphere

Keep up to date with your favourite Rails bloggers in context.

Read more about how it works


Oliver_clarke regenerate paperclip thumbnails

by Oliver Clarke | 3 days ago | Read more

Paperclip is a cool new alternative to attachment_fu for uploading files in Rails. (There’s a good tutorial on Jim Neath’s blog) The only gotcha I’ve run into so far is regenerating thumbnails. With attachment_fu, you just re-save your models. For Paperclip, there is a rake task. rake paperclip:refresh CLASS=YourModelName Hopefully that saves someone ten minutes of Googling :)

Headshot2 @xentek Watch, learn, weep tha…

by Damien McKenna | 3 days ago | Read more

@xentek Watch, learn, weep that you don’t code in Ruby :P http://tinyurl.com/5ktcbl

Headshot2 Here’s an awesome zipcode find…

by Damien McKenna | 3 days ago | Read more

Here’s an awesome zipcode finder site, complete with awesome error messages: http://tinyurl.com/57r2pw

Жизнь животных

by Igor Gajsin | 3 days ago | Read more

В понедельник прокуратура Москвы направила в суд уголовные дела двух молодежных групп, обвиняемых в совершении в период с августа 2006 года по октябрь 2007 года 22 убийств и более 20 нападений по мотивам национальной и расовой ненависти. Среди этих арестованных подростков-скинхедов оказался 18-летний Павел Скачевский.

Сегодня днем шесть лиц кавказской национальности напали на его родную сестру. Неизвестные действовали организованно. Избивая женщину, они выкрикивали «смерть фашистской семье».
- Я забрала двухлетнюю дочку и шла мимо детского сада с коляской, - рассказывает 26-летняя Екатерина Скачевская, - в ней мои четырехмесячные близняшки. Около забора стояла группа неизвестных мне парней лет семнадцати. Южане что-то горячо обсуждали, а потом один из них показал на меня пальцем. Они подбежали ко мне внезапно, и не обращая внимания на детей, стали избивать. Они хватали меня за волосы, били ногами в живот и руками по голове. При этом выкрикивали «смерть фашистской семье».

Избив 2-летнюю малышку, подонки стали вырывать из рук женщины коляску, пытаясь ее перевернуть.

- Я повисла на ней всем телом, пыталась удержать, - продолжает женщина. - Спас нас сосед по дому. Он закричал на них и даже попытался догнать, но они убежали.

Екатерина отделалась ушибами головы и живота, старшая дочка сильным испугом и травмами ног. Пострадавшим зафиксировали побои в поликлинике, куда были вызваны сотрудники ОВД «Печатники».

Возбуждено уголовное дело по факту организованного избиения на столичной улице женщины и ребенка

источник: http://www.kp.ru/online/news/109174/print/
наводчик: http://beekjuffer.livejournal.com/517381.html

User_3321_200x200 Кофейные ссылки #3

by Alex V. Dmitriev | 3 days ago | Read more

Сегодня под кофе читаю Rails Envy. Самое интересное для меня:

На закуску вакансия:

49 Nice And Creative Error 404 Pages

by Lim Hong Kiat | 3 days ago | Read more

Whether you have a broken link on your site or your visitors happened to come from a site that incorrectly hyperlinked your site; they are likely to land on a error page. If this error page is properly handled, the visitor will be reading a Error 404 page. Seeing things from a visitor’s point of [...]

My120_135 RE: как сделать опрос на сайте

by Ruslan Voloshin | 3 days ago | Read more

спасибо!

Using jQuery with Rails

by Marcel Scherf | 3 days ago | Read more

There’s a nice plugin which acts as a dropin replacement for prototype and scriptaculous in Rails. It’s called jRails and is just a simple plugin. It replaces all the helper methods to use jQuery instead of prototype and scriptaculous. Get it here: http://ennerchi.com/projects/jrails Or install it with this command: ./script/plugin install http://ennerchi.googlecode.com/svn/trunk/plugins/jrails and copy all the javascripts to your [...]

Clear a floating element without additional markup

by Marcel Scherf | 3 days ago | Read more

Found at: Position is everything Normally you would add an element like this: <div style="clear:both">&nbsp;</div> after your floating elements to clear them. With this method you don’t need to do this anymore. Just add this to your stylesheet: .clearfix:after { content: "."; display: block; height: 0; clear: both; [...]

Ads for Adobe PDF, New Revenue Stream For Online Doc Publishers?

by Lim Hong Kiat | 3 days ago | Read more

Do you know you can place contextual ads on PDF files and earn some money from it. Adobe launches Ads for Adobe PDF, a free service that allows PDF publishers to embed Yahoo ads on it. Getting started Here’s how it’ll works. To get some ads up your PDF files, simply upload them to Adobe for ads [...]

Make a Photography Tell Vivid Story

by John S. Kim | 3 days ago | Read more

There is a saying that a picture is worth more than thousand words. So to speak, a picture tells story to viewers more vividly than plain text stories. Furthermore, if image met illustration, an impact of the story would be amplified. Let’s take a look at the pictures below: - Images from http://designyoutrust.com/2008/07/03/where-photography-meets-illustration/ Illustration that is inserted on [...]

Double Shot #241

by Mike Gunderloy | 3 days ago | Read more

Happy July 4th - a day I can catch up a bit while email is quiet, I hope. Programmer Competency Matrix - This one has been going around. I think the basic idea that you can measure a developer’s competency by this sort of checkoff list is nonsense, though; it tells us more about the particular [...]

links for 2008-07-04

by Marcus Ahnve | 3 days ago | Read more

ThoughtWorks: A software socialist’s crusade - Mar. 14, 2008 Fortune on ThoughtWorks and Roy (tags: ThoughtWorks art)

394107515_801e417f25 iftop - Find out who is eating your bandwidth

by Libin Pan | 3 days ago | Read more

iftop: display bandwidth usage on an interface How to install? Download and install the Universal Binary from here Or if you already have MacPort installed sudo port install iftop How to use it? run “ifconfig -l” or “/Applications/Utilities/Network\ Utility.app” to get your network interface id. In my case is ‘en1′, so I just type into Terminal: sudo iftop -i en1 Enjoy! Tales From The Command [...]

Pitophoto_sm Quote of the day

by Pito Salas | 3 days ago | Read more

“Make no little plans; they have no magic to stir men’s blood” – the great city builder Daniel H. Burnham

We are the fleece

by Jonathan Stegall | 3 days ago | Read more

Enjoy a previously scheduled post, as we are spending time in the middle of nowhere at Cornerstone Festival. When I was in college, one of the professors with whom I felt I resonated most was Dr. Mike Rakes, who is now the pastor of Winston Salem First Assembly of God. He is a man with a [...]

288887654_94e759eb3c_m Fire Eagle [del.icio.us]

by Jorge Mir | 3 days ago | Read more

288887654_94e759eb3c_m A Rails 2.1 case study [del.icio.us]

by Jorge Mir | 3 days ago | Read more

upgrading the Insoshi social networking platform

288887654_94e759eb3c_m Baseball Boss [del.icio.us]

by Jorge Mir | 3 days ago | Read more

Passenger <3 Sinatra

by Nick Plante | 3 days ago | Read more

A couple people have asked me how I'm hosting the Sinatra-based pastie service we wrote in yesterday's revised tutorial. The previous version ran on a mongrel handler frontended by nginx, but for this version I decided to try something a little different.

One of the big announcements at Railsconf last month was that Passenger (aka mod_rails) would be releasing a v2.0 with support not only for Rails applications but also for Rack, meaning that any Rack-based Ruby web framework can also run on it. Yay for deployment options, right? So anyway, I figured we'd give that a shot.

For those of you who haven't yet mucked with it, Passenger is dead simple to setup. Run gem install passenger to pull down the gem, and execute the passenger-install-apache2-module command to build and install the Apache 2.2 module (you'll need the proper Apache libraries to be present of course). The command output will show you how to configure Apache to load the module.

Getting Passenger to run a Sinatra-based application also turned out to be remarkably easy. All you need to do is create a regular old Rackup script. The file will need to be named config.ru and should contain all the logic necessary to initialize our app:

require 'rubygems'
require 'sinatra'

Sinatra::Application.default_options.merge!(
  :run => false,
  :env => ENV['RACK_ENV']
)

require 'toopaste'
run Sinatra.application

Place this file in the folder on your server where toopaste.rb and the views directory reside.

Next, create a public directory. This is where any static images, JavaScripts, or stylesheets would be kept (we're not using any, in this simple example). Point your vhost's DocumentRoot here:

<VirtualHost *:80>
  ServerName paste.zerosum.org
  DocumentRoot /var/www/apps/toopaste/public
  ...
</VirtualHost>

You might as well create a tmp directory too. You can place a restart.txt file in this directory to tell Passenger it needs to reload the app without restarting Apache (you can use this in your cap restart tasks, too).

Couldn't be much easier. For more information on deploying other Rack-based frameworks (Merb, Camping, Ramaze, etc) and various other config options, check Passenger's user guide.

Open a file by name…

by Tom Lianza | 3 days ago | Read more

If you’re working on a software project of any magnitude, you’ll have a bunch of source files and will often need to jump between them. Most of the IDE’s I’ve used have convenient keyboard shortcuts to let you open a file by name without browsing around with a mouse: IntelliJ: “Goto File” - Ctrl Shift [...]

Me "OH: the trick is to write your unit tests while you’re sober. then write the code while..."

by John Reilly | 3 days ago | Read more

“OH: the trick is to write your unit tests while you’re sober. then write the code while you’re drunk”

- technoweenie

links for 2008-07-04

by Vishnu Gopal | 3 days ago | Read more

Ericsson: Telecom web services Parlay/X (tags: parlay sms mms operator) ratproxy - Google Code (tags: security web development)

links for 2008-07-04

by Mike Pence | 3 days ago | Read more

Pathfinder Development » Pretty blocks in Rails views (tags: rubyonrails blocks views helper) Giles Bowkett: Fear And Loathing At RailsConf Giles at his best

Porn and Piracy? Oh come on…

by Warren Seen | 3 days ago | Read more

Repost of a comment submitted to this piece on Business Spectator, in case it gets edited or does’t end up being posted at all. Hackles raised, set phasers to KILL. You had me nodding my head until the last paragraph, what a ridiculous conclusion! The argument that all the Internet is used for is piracy and [...]

Headshot2 @xentek weird. Just do zennawa…

by Damien McKenna | 3 days ago | Read more

@xentek weird. Just do zennaware dot com

It's just a difference of opinion...

by Jonathan Clarke | 3 days ago | Read more

As so often happens in the world of software, someone aquires a version of Dreamweaver and instantly think that the website that they have spend hours working on is now the bees knees.  Everyone has gotten this feeling at one time or other, I certainly have (blinking lights and ms clip art was all the rage back in the 90's).

A guy I knew during my my time in Dalian, China, got back in contact today proclaiming that he now has an outsourcing team asembled working as soldiers of fortune. Their mission, to crack open the mythical giant of the US & EU software industry and reap the rewards.  Anyhow, we get to chatting about the venture of his and his plans for world-wide domination, he then shows me his website.

Epic Fail

My eyes are still bleeding, it looks terrible, it is terrible, small children would run away from this colourful behemoth, grown adults would roll into the fetal position and cry out for their mother.  Let's just say it was bad.  So anyhow I proceed to give him the benefit of the doubt, I remember saying that blue backgrounds full of ships and bright yellow links have no place in an outsourcing website, that the 90's want their webpage back, that messages to their customers should never contain the phrase "Just do it ,man!!!" and above all that practice of harvesting links pointing to the 90% of the worlds spam resources is just one very bad idea.  

To top it all off, during my browsing of this site (I was wearing protective glasses at the time), I was infected with a number of nasty trojans and viruses.  My friend has become a spam king.  He was wondering why he had no US & EU clients, so I gave it to him straight.  Every company, usually gets to give their first impression via their website, getting infected with anything is always a negative in their view.  These days so many mediums of information are are all inspected before a deal is done to ensure that the opposite party is legit.  My first google search for my friends page yielded results of Viagra, Erectile Disfunction and JS_DLOADER.JS, it's a very weird combination.  

One thing I always noticed was a huge divide between website design in the western world and design in China.  It's not a bad thing, it's a matter of culture.  I always equated it with walking down the main streets of the respective cities, in the middle kingdom you are faced with glaring neon lights proclaiming KTV bars, electronics and noodles, Ireland, thankfully, is a bit more quaint in that regard.  So when I see websites in China with all the bells and whistles I don't particularly pay much notice but do spend a lot of time trying to see past the junk for the nuggets of gold that are off to some side.  In the western world, things are much more minimalistic, each page focuses on a specific are, one which automatically draws the attention to the users point of view.  At the end of the day, it is chalk and cheese, I would have great difficulty designing any Chinese site and vice versa.  

I do hope that he takes some of the advice I gave him, but I doubt he will.  I'm a minimalist type of guy, I like clean lines, some curves and good content.  Flash, FLEX, Silverlight, well those are things I am not into, sure they have their uses, can look very eye-catching but mostly they are just used for evil purposes.  I know what I like and can definitely tell you what I hate.  Bells and whistles = FAIL.  Spam url's = EPIC FAIL....

Viacom has got balls....

by Jonathan Clarke | 3 days ago | Read more

Youtube, you're screwed

Viacom had astonishing balls to ask for the source code for the search functions that power Google and YouTube, the source code for YouTube's new "Video ID" program, a complete set of every video ever removed from the site, databases containing information on every video ever hosted at YouTube, and a copy of every private video.

So in the ruling by a Judge in the District of New York awarded Viacom's representatives to all of YouTubes logs.  I have a number of concerns about this whole debacle which I'll talk about here. What the hell is Google doing with over 12 Terabytes of data just containing logs?  I can really sense EU lawyers salivating over this, the EU have unbelievably strict privacy laws. 

Why was Viacom looking for access to source code? There are hundreds of cloned services out there that mirror YouTube, they were not the first to create this service, obtaining and possibly leaking code would just enable more clones to be made available.

Whatever happened to YouTube's amazing technology that would automatically weed out copyright content from the site?  Was this implemented?  If so, how many videos were removed as a result?  Who are Viacom looking for information on, uploaders or the actual content consumers?

Lastly, I personally find it hilarious that Viacom were requesting the search technology behind Google and Youtube.  They are the same technology, can you imagine for one second Viacom actually aquiring the most intimate details of Google's core business?  That's right, neither can I. What is really astonishing is that a division of Viacom, CBS, has major deals with Youtube, that involves having a large CBS channel within the site.  

It's fast becoming very clear that despite all the press releases and lawsuits there is a major battle waging between old media and new.  Content owners are trying to figure out what to do and how to do it before the old medium of television dies a lonely death (Not for some time I expect).  Youtube, Justin.tv, and many more of it's ilk, divide and conquer. 

Google may shortly begin regretting buying the service,  .  Mark Cuban once famously commented “Only a ‘moron’ would buy YouTube”, he may be right after all.  These types of lawsuit are only the tip of the iceberg.  It happened with book publishers, it has happened with radio, it's happening with record labels and artists.  Video is the new battleground...

Technorati Profile

Avatar Scrubyt perks and rules

by Scott Motte | 3 days ago | Read more

-It will skip over tbody for xpaths. Don’t include it in your xpath. # correct content '//body/table/tr/td # incorrect content '//body/table/tbody/tr/td -It will skip over font[@size=n] but not over just plain font -extractor.to_xml will output to the xml you specify within the: extractor = Scrubyt::Extractor.define do .. end -extractor.to_text i’m not sure how to work

ar_mailer gem forked on GitHub, goodies added

by Adam Meehan | 3 days ago | Read more

Now that GitHub has a gem server it allows the process of managing your own fork or customisation of a gem ridiculously easy. No need for your own gem server or shipping around gem files, just put it up on github and nominate it as a gem in the project config. GitHub will automatically compile [...]

Akitaonrails Off-Topic: Novos Planos na Locaweb

by Fabio Akita | 3 days ago | Read more

Galera, começamos a lançar alguma novidades aqui na Locaweb. Tem muito mais por vir. Mas para começar, foram para ar os novos planos de hospedagem compartilhada.

Resumindo, pelos mesmos preços, começando em R$ 18, agora temos 25 vezes mais espaço, 10 vezes mais domínios, 10 vezes banda e bases MySQL ilimitadas em todas os planos. Vejam mais detalhes aqui.

Como exemplo, no Plano Expresso isso significa 5Gb de espaço em disco, 100Gb de transferência mensal, 50 domínios. Acho que isso deve tornar as contas mais atraentes aos brasileiros.

Falando nisso, estou bastante ocupado por aqui :-) Temos muita coisa legal no forno. O Trial de Rails ainda está em andamento mas as inscrições já foram fechadas porque temos mais gente do que esperávamos! Peço desculpas pelo atraso em liberar algumas contas, mas estou terminado as últimas ativações, ufa! Aguardo o feedback de vocês!

links for 2008-07-03

by Tom Armitage | 3 days ago | Read more

Trackmania: World Record Trailer | Rock, Paper, Shotgun “250 Trackmania players racing round the same track.” Beautiful; unlikely the merged-replay videos, these are real simultaneous players - and there’s still that lovely, fluid flow to it. I need to play this more than ever. (tags: trackmania video flow games racing record simultaneity) Younghee Jung » Blog Archive » [...]

Cheatsheets al alcance de la consola

by Sergio R. de la Garza | 3 days ago | Read more

Es bueno tener cheatsheets a la mano, un buen amigo dijo: “No puedes aprenderte todas las funciones y métodos de memoria” y tiene razón. Aquí hay una herramienta con sabor a Rubygem que nos puede ayudar a consultar cheatsheets de diferentes lenguajes. Todo lo que hay que hacer es: $: sudo gem install cheat Ejemplos: $: cheat wife wife: Cheating [...]

Avatar Scrubyt screen scraping tutorials

by Scott Motte | 3 days ago | Read more

I am beginning to use scrubyt gem and in my opinion the documentation and examples are pretty bad. The name isn’t the greatest either. It’s difficult to type so be careful in the following examples. (should have just called it scruby or scrubby or something. the t is annoying.) **However**, I am starting to understand how [...]

Ipj6kg0tr60seydmsy5q94wd_500 Perfect weather out on the patio

by Tyler Love | 3 days ago | Read more



Perfect weather out on the patio

weka

by Steven Ness | 3 days ago | Read more




Making predictions with Weka

Saving and loading models

You save a trained classifier with the -d option (dumping), e.g.:


java weka.classifiers.trees.J48 -t /some/where/train.arff -d /other/place/j48.model


And you can load it with -l and use it on a test set, e.g.:

java weka.classifiers.trees.J48 -l /other/place/j48.model -T /some/where/test.arff


weka commandline primer
Running weka from the command line
AddClassification
[Wekalist] How to attach instance IDs to classified instances?
Batch Filtering in Weka




For Those Using Internet Explorer 6: Please Stop

by Robert Fischer | 3 days ago | Read more

In response to 37Signals announcing that they will stop supporting IE 6, I checked my Google Analytics and discovered something surprising: 7% of EnfranchisedMind readers still use IE 6.

To them, I say — PLEASE UPGRADE. And let me know why you’re still using it — I’m really, genuinely curious.

So, why should you upgrade? I’ll quote 37 Signals:

The Internet Explorer 6 browser was released back in 2001, and Internet Explorer 7, the replacement, was released nearly two years ago in 2006. Modern web browsers such as IE 7, Firefox, and Safari provide significantly better online experiences. Since IE 6 usage has finally dipped below a small minority threshold of our customers, it’s time to finally move beyond IE 6.
[...]
IE 6 is a last-generation browser. This means that IE 6 can’t provide the same web experience that modern browsers can. Continued support of IE 6 means that we can’t optimize our interfaces or provide an enhanced customer experience in our apps. Supporting IE 6 means slower progress, less progress, and, in some places, no progress. We want to make sure the experience is the best it can be for the vast majority of our customers, and continuing to support IE 6 holds us back.

More information can be found at the Stop IE6 Campaign. Specifically, see the Top 10 Reasons (there are actually 12 of them…).

As Internet Explorer 8 cruises into being, can we please agree to put to death this ancient, buggy, insecure piece of code?


© 2008 Robert Fischer and Brian Hurt. This article was a post on the EnfranchisedMind blog. Creative Commons License
The EnfranchisedMind blog is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License. (Digital Fingerprint: bcecb67d74ab248f06f068724220e340 (66.150.96.121) )

Monsoon Clouds

by Dagny Gromer | 3 days ago | Read more

Right on schedule for the Prescott July 4th Rodeo, a monsoon storm builds to the south of Town. This is a panorama composed of 4 images, combined by PhotoShop.

Workplace Utopia is a Myth: Darn

by Alain Yap | 3 days ago | Read more


When meeting new people, I think there are far more first questions about work than even getting the names right. That says something about how people view themselves and others as opposed to 'being'. Human knowing, human working, human doing and not human being. Hope you get the point.

Being said that, invariably, most people want dream jobs and so dream workplace environments. Some, like me, are able to peddle wares without leaving home. Oh, the many ooohs and ahhs I get. But it is far from being rosy as the lines between personal and household time gets blurred with being 'productive'. Still weighing the pros and cons, I'd rather not spend money on gas and big plus is I get to be with my kid.


My point is workers can only be grouped as a collective in terms of earning money (why's and w's of salary) and work results or outcomes (the product or services the group contributes to). As far as needs, wants and other interests - it is mostly anybody's guess. Short or long leash, wads or trickle of money, own space or group space - the list goes on. What will
work (pun unintended) is dependent on deep personal interests as they are aligned with company vision. And as these two intersect more than diverge, I think it is as close to a good match as there will ever be. Calling it work won't suffice; I'd rather it be called 'life's work'. Awww.

And we thought
Sergey and a few lucky (or duh) ones had it good. But to each his own and to thine self be true. Just in Nick of time for this post.

So 'What should I do with my life?'

Headshot2 @blaix You need to go get that…

by Damien McKenna | 3 days ago | Read more

@blaix You need to go get that done! ;-)

Valparaiso, Chile - Desarrollador web 2.0 en Designa grupor creativo

by Ismael Celis | 3 days ago | Read more

Necesito para mi empresa un desarrollador web 2.0 con buenos conocimientos en CSS + PHP + AJAX + MYSQL para desarrollar proyectos web. La oferta esta abierta para desarrolladores de la region de Valparaiso que puedan asistir a nuestras oficinas 1 o 2 veces por semana para cordinar los proyectos. Debe tener experiencia demostrable en el area con proyectos que apliquen las tecnologias anteriormente mencionadas. La remuneracion es por proyectos y la calidad es bien pagada. Saludos.

Cutting corners with xmpp4r-simple

by Vladimir Dobriakov | 3 days ago | Read more

xmpp4r-simple aims to provide a wrapper around the powerful and well maintained xmpp4r library, "making it dead-simple to send and receive Jabber messages". Unfortunately, the abstraction and simplification provided by xmpp4r-simple is leaky, missing the principles of jabber protocol. The...

Two stories about light and information

by Matthew Katz | 3 days ago | Read more

When I was younger I saw small haloish ripples around some shadows.  I thought I had magic powers, that I could see auras.  I believed I had this secret power for quite some time.  While reading a moving presentation by Matt Web about ancient Patagonian communication (it’s sort of heartbreaking), I learned what it was.  [...]

Headshot2 @xentek Another SVN client for…

by Damien McKenna | 3 days ago | Read more

@xentek Another SVN client for you to try out: http://tinyurl.com/4rnnhu

Portrait Refactoring an ActiveRecord callback

by Josh Nichols | 3 days ago | Read more

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.

MapReduce at RailsConf Europe

by Jonathan Dahl | 3 days ago | Read more

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.

Checkbox list in Ruby on Rails using HABTM

by Justin Ball | 3 days ago | Read more

Checkboxes are one of those things that look easy and should be easy, but they aren’t always easy. I needed a solution that could create a checkbox list of languages that a user speaks. So I don’t forget here’s how to do it: The migrations are important. You have to be sure [...]

Twitter Updates for 2008-07-03

by Marcus Ahnve | 3 days ago | Read more

Calling Telia is painful. After talking to the ‘intelligent’ machine I am now supposed to wait for 28 minutes. There is no email option. # Telia is 10x more expensive on international calls than Telenor. I thought that was a mistake, but apparently it is not. # Anyone using Callex for international calls? http://www.callex.se # Or Voyo? http://www.voyo.se [...]

1200033289_m Cattle Brands

by Jordan Dobson | 3 days ago | Read more



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!



» Email This  » Post A Comment!

Slobodan-110x110 SproutCore - a javascript framework

by Slobodan Kovacevic | 3 days ago | Read more

SproutCore is a javascript framework which tries to enable developers to build web apps that look and act more like a desktop apps. It steps away from a classic web app model by moving a lot of app into the browser itself, which then interacts with server via AJAX. As it says on the SproutCore site: After [...]


Tell us what you think of the new BlogSphere feature. We are continually looking to improve and update the functionality based on your feedback.

Job Board

Job Boards
Find your next Ruby on Rails project or job.
Exclusive content, regularly updated - onsite and tele-working positions listed.

View the opportunities

Latest from the Weblog

Recent Recommendation

Marshall Sontag:

My go-to man for rails questions.

- Sbubble J.Z, United States