Ever since I moved to the new blogging engine, some of the older posts had destroyed markup (thanks to a wild mixture of markdown, smartypants, html, wordpress, …).

I could easily fix single posts (e.g. the "Pages";) by opening them in the admin interface and clicking the save button. Enki (my current blogging engine) would then interpret the imported markup-code and save a plain xhtml version to the database. This repairs most of the linebreak/newline stuff.

As I don't want to do that on each and every post by hand, I decided to use the rails console to do that work for me :)

The console script is found in the "script/"; folder of a rails project and can be started by simply issuing a:

"ruby /script/console production";

This will open up IRB, the interactive Ruby shell, with all classes belonding to my Rails app preloaded.

Let's first check how many posts we have

1
2
3
4
5
Loading production environment (Rails 2.3.2)
>> Post.all.class
=> Array
>> Post.all.size
=> 1012

Awesome, we now know how we can get an Array containing all of our model objects.
To know which methods to call for each of those objects, we can take a short look at the "Posts"; model and see things like these:

1
2
3
4
5
6
7
8
9
  def minor_edit
    @minor_edit ||= "1"
  end

[...]

  def apply_filter
    self.body_html = EnkiFormatter.format_as_xhtml(self.body)
  end

Knowing that we are using a Rails app, there should also be a save() method provided by Active Record.
If we now combine all of those things together, we end up with a way to simply go though all the posts, marking it as a minor edit (otherwise they'd show up again in RSS I guess), running the filter function and saving it back to the database:

1
2
3
4
5
Post.all.each do |single_post| 
   single_post.minor_edit 
   single_post.apply_filter
   single_post.save
end

Done :)

Comments