The Django’s automatic administration generator is nice. With three lines, you have an interface to add, update and delete datas.
However with textareas, it might be useful to have a more advanced editor.

So we’re going to see here, how to implement TinyMCE to the textareas in a specific administration page.
But this technic can also work with FCKEditor or any other WYSIWYG editor. All you have to do is put the appropriate javascript.

Let’s our application’s admin.py

from django.contrib import admin
from project.application.models import Page
class PageAdmin(admin.ModelAdmin):
    list_display = ('name', 'url')
    fieldsets = [
        (None, {'fields': ['name', 'url']}),
        ('Content', {'fields': ['content']}),
    ]
admin.site.register(Page, PageAdmin)

We define an admin interface for our model Page with the fields name, url and content.
It’s the last field that will be a TinyMCE field.

Let’s start by adding external javascript files for this model.
After fieldsets[], add :

class Media:
    js = (
        '/js/tiny_mce/tiny_mce.js',
        '/js/admin_pages.js'
    )

We include those two supplementary documents in the admin page for the model Pages. And only this one.

Install tinymce in the folder /js/. And create the file /js/admin_pages.js in which you’ll put :

tinyMCE.init({
    mode : 'textareas',
    theme : "simple"
});

So you’ll transform any textarea in this page to a TinyMCE field (in our case, there’s only one).
Restart your application and look at your nice text editor :)

You can now add any javascript to any admin page this way.

If you’ve already been using Active Record. And as you’re reading this blog and this article, I suppose you have, even though you may not know you have, you know how it is powerful.
In case your memory fails you, active record is the list of methods used to access databases in Ruby on Rails.
It is compatible with MySQL, SQLite and PostgreSQL (and if you wish to add your own adaptor, you can quite easily).
But Rails is a framework for web applications. And God knows the web isn’t the only face of computer programming.
So we’ll see how easy it is to use Active Record without Rails (or without all rails as activerecord is a part of it).
First of all, you need to install the library. If you already Rails installed on your server, you’re ready to go. Otherwise, do the following :

gem install activerecord

It’ll get the latest stable version of the library and install it on your computer.

Now, let’s start having fun with some code lines :)

Create a new document named (for example) main.rb.

First, you need to call the rubygems and activerecord libraries.

require 'rubygems'
require 'active_record'

With those lines at the top of your document, you now have access to all the methods provided by Active Record.

So let’s use them.

ActiveRecord::Base.establish_connection(
    :adapter => 'mysql',
    :host => 'localhost',
    :user => 'root',
    :password => 'root',
    :database => 'test'
)

This will instantiate the library.
<em>However, it'll not connect you to the database. You're getting connected only when you do the first query</em>

We now need to create a model.
I invite you not to create it in the same document. So create a document named "user.rb" in the same directory as your main.rb.
Put in that new document :
[code lang="ruby"]class User > ActiveRecord::Base
end

And in your main.rb, call it.

require 'user'

You now have access, in your main.rb, to the object User, which is a child of ActiveRecord::Base and grants it all the usual methods available to Ruby on Rails models. However, you're not in a rails application.
So let's get all our users.

p User.find(:all)

Based on the fact that the table "users" exists in your database "test", this will print in your console the hash of all your users.

You can now do anything you want using ActiveRecord in your Ruby console or offline user interfaces applications.

But wait it's not over. Until now, we've defined all our configuration datas directly in the program. And that's very bad. So we need to add an external database.yml document.

adapter: mysql
host: localhost
username: root
password: root
database: refcrawler_dev

And to load that external document in ours to get it's values.

require 'yaml'
dbconfig = YAML::load(File.open('config/database.yml'))
ActiveRecord::Base.establish_connection(dbconfig)

I’ve been tagged by Otto to do this little game.

The rules:

  • Link to your original tagger(s) and list these rules in your post.
  • Share seven facts about yourself in the post.
  • Tag seven people at the end of your post by leaving their names and the links to their blogs.
  • Let them know they’ve been tagged.

7 facts about myself that most people don’t know:

  • Contrarily to what most of the peoples I’m tagging back apparently think (or are joking about), I’m not gay. I love women and I’m proud of it ! ;)
  • I live with 4 other roommates (and there’s one room left for a 6th) in a presbytery.
  • I often go to the cinema (at least once every week); I watch a lot of tv series (always in original version and on my computer). But never the tv.
  • I’ve been scout for more than 10 years.
  • I was born the day before Tchernobyl (same year of course).
  • I have three names : Damien, André, Marceau. The second and third ones are the names of my grand fathers.
  • I’ve been celebrating my 18th in a bus going to Polland.

My 7 tagging victims

  • Flofliflon : because her blog is very new and she’s never been doing that exercise yet.
  • cmic : my soulmate, refering to the last dmoz mozzie awards (we won the award « Cutest Couple » together)
  • jeansboub : because he never writes anything on his blog (even though he’ll never follow it).
  • mll : because I don’t know (yet) where his blog is hidden
  • Pierre : my little brother. So like that he’ll do something else than writing poems.
  • glooze : because « c’est la looze ».
  • pocky : because I win the battle AND the war.

Note to them : you don’t have to write your article in english. French will be fine.

As you might already know, Google is currently migrating feedburner accounts to a new system working with Google accounts.

However, as a change, the thing doesn’t seem to be working.
Result : even though they’re saying my feeds have been successfully migrated, I don’t have access to them anymore.

So I had to create new ones. And I invite you to change them in your reader.
RSS feed in English.
RSS feed in French.

This is the first article of a serie of comparisons between PHP and Ruby.

Count the number of words in a text is much more complex than what you should think first.
Because a space doesn’t  mean a new word everytime. There can be interrogation points with spaces before and after for example. And an interrogation point isn’t a word.

Here, we’ll take the following definition for « word » :
Two or more characters with at least one alphabetical character..

In other words : at leat two characters with at least one letter of the alphabet.

Let’s count our words in Ruby :

class String
    def nb_words
        self.split(/[a-z]+/).size
    end
end

To count the number of words, we only have to do :

puts "my string ! Great no ?".nb_words

Which will then give us 4 and not 6. « ! » and « ? » aren’t words.

Let’s now do the same thing in PHP.
Even though I don’t think it’s a good idea as there’s the function str_word_count.

function nb_words($string) {
    return count(preg_split('[a-z]+', $string));
}

To be used like the following :

echo nb_words('my string ! Great no ?');

It’s very easy, in Ruby, to count the number of days between two dates.

date1 = 1.month.ago
date2 = Date.today
puts date2-date1

However, you might need to calculate, not all the days between dates. But all the week days. For example if you’re working on an extranet and you want to count all the working days :)

Vamos ! Let’s put in your code (wherever you want. But put it somewhere logical please) :
class Date
def weekdays_until(date)
return 0 if date <= self
(self..date).select{|day| day.is_weekday?}.size
end
def is_weekday?
self.wday != 0 && self.wday != 6
end
end

And to use is :
1.month.ago.weekdays_until(Date.today)

Cool no ? :)

What are we doint ?
We overload the object Date by adding to it two new methods :
- is_weekday? which gives us true if the day is from monday to friday.
- weekdays_until which gives us the number of days from monday to friday only.

If course it doesn’t count the holidays ;)

Note : the tricks used here, like 1.month.ago are only available if you’re in a Rails environment. Otherwise, you have to calculate this by hand.

A french guy, named Eric Dupin closed his blog, called presse-citron because he’s tired of all the trolls in comments there. It’s only temporary as he’s planning to come back. But I want to react on that action.
Not because I don’t support it, all the contrary.

Even though I don’t really like the guy, who fakes to be an expert to make money with his blog, I completely agree with this action he’s doing. I am also tired of all those trollers.

A lot of web users thinks they can do anything on the internet because on the first look, anyone seems to be anonymous. But this anonymity is as virtual as all the web is. And Eric isn’t the only one to manage newbies who are really good at criticism. But not constructive critisicm.

As an example, until last year, I was moderator on a french SEO forum, called WebRankinfo. There was there an ODP forum for which only utility was to provide informations to users and allow communication between editors and users.
Well this forum have been closed one year and a half ago because of those trollers who made it’s management unbearable.
I was moderator there at that moment. And the trolls were depressing like you can’t imagine from my editor point of view.

So Mr. Dupin, my only message is : you’re not the only one to have to manage that kind of message in permanence. Be brave. You’ll see with time, you’ll learn to ignore them and forget them 3 seconds after reading it.

Note : because of battery problems, there’s no photo at the end of my articles for now.

You probably already know (otherwise, I highly invite you to read the Ruby on Rails bases) how easy it is to validate datas with our favorite framework :)

if myDatas.save
#The datas have been saved
else
#There's an error. The myDatas.errors contains it.
end

After that, you only need to add some validation parameters for the datas in the model.
But now, let’s guess others validations cases, a bit particular that doesn’t enter in the « normal » case.

You only need to create a new method which will come validate your datas (the example above is completely fake) :

def validates_roxitude(*attribute)
reg = Regexp.new '/^ruby(.*?)rox$/'
self.errors.add('rox', 'Hey, Ruby rox. You have to say it !') unless reg.match attribute
end

Here, we declare an error except if the field starts par « ruby » and ends by « rox ».

We only need to force the validation with this method for our field and Ruby rox ! ;)
class myModel < ActiveRecord::Base
validates_roxitude :myField
end

I changed my cellphone two weeks ago. After having a Sagem myx6 during a bit more than two years, I wanted to show how geek I am.

So I decided to pick up the new Nokia e71.

With the appropriate subscription of course. One allowing me to have illimited internet access (and illimites SMS because I’m under 26).

And for now, I’m sincerely very happy of it. Whether with the cellphone funtionnality, the internet or the MP3 player, I couldn’t have found better :)
So if you want to pick up a new cellphone, you know which one I would advise you ;)

 
Fork me on GitHub