Mon May 04 01:18:00 UTC 2009

Radiant - repositories at GitHub

Posted in Links, Radiant CMS at 01:18 AM by mohits

These are the main repositories that you may need to keep an eye on, if you’re working with Radiant.

Also, keen to see what this offers: http://github.com/phallstrom/pastefree/tree/master

Sat Aug 09 22:00:00 UTC 2008

Using Ruby to get information about a DBF file

Posted in Ruby at 10:00 PM by mohits

In a previous article, I had written about getting started with the DBF gem to convert a DBF file into a CSV file. In this article, I show how to get basic information about a DBF file by using the gem.


1
2
3
4
5
6
7
8
9
10
11
12
13
require 'rubygems'
require 'dbf'

table = DBF::Table.new(ARGV[0])

puts "Information about #{ARGV[0]}\n\n"
puts "Schema in ActiveRecord Format:"
puts table.schema
puts "\nNumber of colums  - #{table.columns.size}"
table.columns.each_with_index {|col, index|
    puts "#{index},#{col.name},#{col.type},#{col.length},#{col.decimal}"
}
puts "\nNumber of records - #{table.record_count}"

Sat Aug 09 21:05:00 UTC 2008

Working with DBF files and Ruby - a simple dbf2csv example

Posted in Ruby at 09:05 PM by mohits

Just a very short note on using Ruby to process DBF files. A number of applications still use DBF files as a simple database format (I’ve since moved on to SQLite3 – more about that some other time) – most importantly, it’s used as part of the Shapefile format.

The DBF Gem

The gem to use is called DBF and it can be got from http://dbf.rubyforge.org/dbf/ – just install it using gem install


command>gem install dbf
Bulk updating Gem source index for: http://gems.rubyforge.org
Install required dependency hoe? [Yn]  Y
Install required dependency rubyforge? [Yn]  Y
Successfully installed dbf-1.0.6
Successfully installed hoe-1.7.0
Successfully installed rubyforge-1.0.0
Installing ri documentation for dbf-1.0.6...
Installing ri documentation for hoe-1.7.0...
Installing ri documentation for rubyforge-1.0.0...
Installing RDoc documentation for dbf-1.0.6...
Installing RDoc documentation for hoe-1.7.0...
Installing RDoc documentation for rubyforge-1.0.0...

Simple Usage

As a simple example, I convert a DBF file to a comma-separated list. In this example, we check the type of field to see if it is non-numeric. Non-numeric fields are wrapped in quotes so that we don’t have to worry about commas in the text. If you are sure that none of the fields have commas, you could just proceed to output them without quotes – or you could use gsub! to replace any commas. Either way, this is just an example!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
require 'rubygems'
require 'dbf'

#Load in the DBF table
table = DBF::Table.new(ARGV[0])

#wraps a field in quotes
def qt(field)
   "\"#{field}\""
end

count = 0

# Convert to CSV and output to stdout
table.records.each do |record|  #for all records
  csvr = []
  table.columns.each {|col|  #for each column in the record
    #Wrap non-numeric fields in quotes
    field = (col.type=='N')? record.attributes[col.name] : qt(record.attributes[col.name])
    csvr << field 
  }
  count +=1
  puts csvr.join(',')
end

puts "[#{db}]\t- processed #{count} records."

When using DBF, you can usually access the attribute by doing something like record.x (if x is the name of the attribute that you want) – this works fine except in cases where the name of the attribute is something like type which will give you interesting results :) That’s why for a generic example, we’ve used record.attributes[col.name] which should work in all cases.

References

Sat Aug 02 21:54:00 UTC 2008

Introducing Summer Reboot - Radiant Documentation

Posted in Radiant CMS, Ruby on Rails at 09:54 PM by mohits

According to their website, Radiant CMS is a no-fluff, open source content management system designed for small teams. In my opinion, it is quite cool and offers a clean codebase, a fantastic extensions system and has a very good community.

The Radiant community has just embarked on a joint project to create a set of documents for Radiant. The project started near the end of June, based on a rough table of contents that would read like a book. It’s hosted off the wiki for the time being. Now, it’s the start of August, so I had sent out a brief update and request to people. This is the update.

[1] As you (may) know, Summer Reboot is targeted as being the starting point documentation for Radiant in the future and so far, we’ve come up with a list of documents that we’d like to create and some authors have claimed some of the articles as things that they would like to write. A few articles are already up!

If you feel there should be more topics, please edit the home page of the documentation to add it in

If you feel you can write some of it, please claim, write and upload

Current authors/ claimants: THANKS for your support.

[2] I understand that some (many? most?) of us are busy and are doing this as a side-project/ free time effort, so I’m thankful to all of you for that. That said, if you think you have some scribbled notes electronically but don’t have the time to upload it, I’m willing to try to do that. I don’t mind spending some time to push out more things. I’ll rewrite what I get, try to replicate it on my side, capture some screenshots and push it out as and when I have the time.

Contact me: tech {at} onghu.com or mohits {at} onghu.com with what you have/ email. If you can do this TODAY (i.e. Friday), I shall try my best to push out what you pass me during the weekend. Once the work week starts again, it gets difficult :(

[3] Everyone reads :) Help us edit the wiki. Go to the site and see the articles that are there. Take a read.

If there are grammatical errors/ missing words, please FIX it

If the explanation is not clear and you can rewrite a part of it, please FIX it

If more information is needed and you can write it, please FIX it

If more information is needed and you can’t write it, please ADD comments into the article, preferably in a color like orange to distinguish it from the main text. Hopefully, someone can address it later.

[4] Ideas from the List: This list has some good ideas and bug fixes or workarounds. If you have the time and spot something that really helps you, go to the wiki and add in at least a small note to the related article. For example, the article on Copy_Move at http://wiki.radiantcms.org/Copy_and_Move has this line at the bottom:


> Known Problems
> There seems to be a problem with using CopyMove with Radiant 0.6.7 in the Development mode.
> This problem does not occur when in Production mode.
> A sample screenshot of the problem is at: http://www.ruby-forum.com/attachment/2380/Picture_2.jpg

If you can, please add such stuff so that people know where to look and when not to panic on ‘known problems’

We’re targeting 31st Aug as the date of launch!!

The Summer Reboot site is at: http://wiki.radiantcms.org/Summer_Reboot

Thu Jan 03 01:00:00 UTC 2008

Codegear Turbo C++ and Ruby

Posted in Codegear Builder | Turbo C++, Ruby at 01:00 AM by mohits

Embedding Ruby into a Turbo C++ (Borland C++ Builder) Application

I’m currently looking at bringing together two of my favourite pieces of desktop software – Ruby and Codegear Turbo C++. I’m still sorting my thoughts out, but here are the main links that will help in getting started. I will write up more details about this once I’ve figured it all out.

The ongoing thread in Ruby-talk that is discussing this issue

Link: http://www.ruby-forum.com/topic/137241

Specific to Borland Builder

Old threads that seem to have a few good pointers and gotchas. These are: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/73326 and very importantly: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/73397

About generally embedding Ruby

A thread that covers the idea and also links to the PickAxe online for this: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/71319

Ruby Embedded into C++

A great tutorial that goes into a lot of detail about the whole process. Link: http://metaeditor.sourceforge.net/embed/

SWIG

You could also use SWIG to connect up between a C/C++ program and Ruby. Link: http://www.swig.org/

As soon as I have the whole procedure worked out, I shall put up a post about the full procedure for integrating between the two of them.

Sat Oct 27 12:22:00 UTC 2007

Online books about Ruby/ Rails

Posted in Ruby, Ruby on Rails at 12:22 PM by mohits

Here’s a small list of online/ free books about Ruby/ Rails. This is just to keep the references in one place. Hope this helps someone else – it certainly helps me!

The PickAxe Edition 1 (Programming Ruby)

http://www.rubycentral.com/pickaxe/

Why’s Poignant Guide about Ruby

http://poignantguide.net/ruby/

Mr. Neighborly’s Humble Little Ruby Book

http://www.humblelittlerubybook.com/

A Little Ruby, A Lot of Objects

http://www.visibleworkings.com/little-ruby/

Quick References on the Language

http://docs.huihoo.com/ruby/ruby-man-1.4/syntax.html

http://www.math.hokudai.ac.jp/~gotoken/ruby/ruby-uguide/uguide08.html

Mon Sep 10 22:28:00 UTC 2007

Radiant CMS - Showing the date of articles

Posted in Radiant CMS, Ruby on Rails at 10:28 PM by mohits

One of my sites (http://tec.onghu.com/) is powered by the Radiant CMS. As I continue to build that site, I shall put up some information about how simple things are done in Radiant.

One of the things that I have is a running list of articles that have been published on different dates. I wanted a simple way to print out the date next to the articles.

Here’s what you need to do for that:



<ul>
<r:find url="articles">
<r:children:each order="desc" status="published">
   <r:unless_content part="no_menu"><li><r:link /> [<r:date format="%b %d, %Y" />] 
</r:unless_content></r:children:each>
</r:find>
</ul>

Notice 2 interesting things in the code sample above.

  1. r:date format – this expects a formatting string similar to what strftime in Ruby/ Rails expects.
  2. r:unless_content part=”no_menu” – this tag is a bit that excludes some pages from being shown in the listing. Any page that has a part called ‘no_menu’ will not be listed. This is a common way to prevent CSS files from showing in the list.

That’s all there is to it. Leave a comment if you want any bit above clarified.

Sat May 26 13:55:00 UTC 2007

"Hello World" using Radiant CMS

Posted in Radiant CMS, Ruby on Rails at 01:55 PM by mohits

If you’re as slow at getting started as I can be at 2:45AM and still insist on trying out Radiant CMS at exactly that time, this small entry may help you getting around to making your first page with Radiant show up.

Pre-requisites

1. Install Radiant as per the instructions

2. Create one project for any of the blog types (this is where we shall steal from) – remember to create the database and adjust the database properties in the database.yml

3. Create your ‘empty project’ – remember to create the database and adjust the database properties in the database.yml

If there’s a need, I could elaborate the first 3 steps further but I think it should be quite easy to follow those steps through.

Adding to the Empty Project

Now, let’s go through the rest. If you read the Radiant mini handbook you will see that it mentions that if you are starting with an empty project, every thing needs to be created – right from the first few layouts, the snippets and of course, the pages. The ‘empty project’ is just that: empty.

Since it took me a while to figure out how to create the first Radiant page, I decided to document that process here for reference.

If you have created a Radiant site, run the bootstrap rake script, started the server, and are logged in, we’re ready to roll.

Step 1: Create a new layout

Click on the “Layouts” tab. This brings up an empty list of layouts.

Then, click on “New Layout”. Give your new layout a name such as “page_style” and fill in stuff that you can copy from a standard HTML web page. Ideally, you should also use some Radius tags in the creation. To cut short the guesswork at this point, I basically stole from the Blog Radiant project that I had installed. This is the cut down code that I copied from there.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
  <head>
    <title><r:title /></title>
    <link href="/rss/" rel="alternate" title="RSS" type="application/rss+xml" />
    <link rel="stylesheet" type="text/css" href="/styles.css" />
  </head>
  <body>
    <div id="page">
      <div id="main">
        <div id="content-wrapper">
          <div id="content">
            <r:unless_url matches="^/$"><h1><r:title /></h1></r:unless_url>
            <r:content />
            <r:if_content part="extended">
            <div id="extended">
              <r:content part="extended" />
            </div>
            </r:if_content>
            <r:if_url matches="^/articles/\d{4}/\d{2}/\d{2}/.+"><r:unless_url matches="-archives/$"><p class="info">Posted by <r:author /> on <r:date /></p></r:unless_url></r:if_url>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

You could also use Snippets, but we’re not going to go there yet. Click on “Create Layout” to, err, create the layout. It should now show the “page_style” layout in the list of layouts.

Step 2: Create a layout for the stylesheet

Click on “New Layout” and give it a name such as “stylesheet”. Then, click on the “More” link below the Name field and enter text/css in the Content-type field there. In the Body of the layout, simply enter the following which means that the content of the file that uses this layout is passed up.


<r:content />

After you click on “Create Layout” it will be saved and will be shown in the list.

Step 3: Add the main page

You already have a layout that can be used as the base layout for pages in your site. Go to the “Pages” tab of your admin site and click on “New homepage” to create the first page. Give the page a title, something like “Hello, World” and then fill out things that will be rendered as the page. I have set the formatting filter to “Textile” and added some text as below


h1. Hello!

This is the first page in the sample site.  
It uses Radiant and uses @Textile@ for the markup.

h2. Creating a List

Using @Textile@, a list is easily created.  I'd like to say Hello to

 * My family
 * My friends
 * My world

h1. Another Level 1 heading


Now, in the bottom bar, select the Layout as “page_style”, the Page Type as “” and the Status as “Published”. With that done, you can click in the top right corner to “View Site” – it will bring up a simple page that shows that things are working! The formatting will look like the default formatting that your web browser applies to the various headings and body.

Step 5: Add a style sheet

In modern web design, it is essential to format the pages with styles. So, that’s a step that we must also look at. There’s only one more thing that needs to be done.

In the “pages” view, we need to create a page that will be the stylesheet for the site. If you look at the layout that we created, there is a line that says:


    <link rel="stylesheet" type="text/css" href="/styles.css" />

That means the page is already set up to serve up a stylesheet called styles.css which should be applied to the page. Only, we haven’t created it yet.

In the “pages” view, click on the “Add Child” item of the “Hello World” page to create a new page. This will be the stylesheet. Give it the name “Styles” and click on “More” below the text field for the name to show the other properties. Very importantly, change the Slug to styles.css – this is the name that it will be served up as. Use no filter, set the layout to “stylesheet” and the status to “published”. Click on the “extended” tab and then on the ”-” sign in the right hand corner to delete that tab. Put the following styling code into the body. To keep it simple, I just added the styling for the headings since we have a few in our default page.


p {margin: 0px 0px 0.5em 0px; padding: 0px; line-height: 1.3em; font-family: arial, sans serif; font-size: 120%; color: rgb(88,144,168)}
h1 {margin: 1.0em 0px 0.5em 0px; font-weight: bold; font-size: 160%;color: rgb(64,64,255)}
h2 {margin: 1.0em 0px 0.5em 0px; font-weight: bold; font-size: 150%;color: rgb(128,128,255)}

Click on “Create Page” to save the stylesheet.

Now, we are done. Click on the “View Site” button to see your site in color!! You might need to refresh the page in your browser just in case it’s being cached. I know it doesn’t look fantastic but it gives you a feeling on how to go on from here. Hope this helps you!

Mon Apr 30 18:38:00 UTC 2007

Backing up a Subversion Repository

Posted in SubVersion at 06:38 PM by mohits

The simplest way to back up a Subversion repository is to make a full backup of it. If your repository is very large, then this may be a bit of a slow process and there are other ways which can be used. However, if you are just looking for the simplest way to ensure that you have a simple backup of your precious repository, then the instructions are very simple!

Backing up

Especially if you use the BDB backend, it is important that you do not access or copy the repository directly. If someone accesses the repository for anything at this time, your backup will be corrupted and quite useless. Therefore, you need to use hotcopy option of the svnadmin command. This ensures that you get a proper comprehensive snapshot irrespective of people accessing the repository at the same time.

More importantly, though, there is a simple Python script called hot-backup that takes as inputs the path of the repository and the path of the backup directory and does the rest. If you have Python installed, this is the easiest way.

  1. Download the script
  2. Change the name to hot-backup.py
  3. Open it in a text editor and change the first line to the directory where Python is installed. In my case, this is #!C:\Python24
  4. Update the paths to ‘svnlook’ and ‘svnadmin’ further down in the script. In my case, these were changed to: svnlook = "C:/DevSupport/Subversion/bin/svnlook" and svnadmin = "C:/DevSupport/Subversion/bin/svnadmin".
  5. Save the script to a directory of your choice. I saved it to: c:\DevSupport\SubVersion\tools\backup
  6. Run it from the command line giving it the repository and backup paths.
 D:\Repository>c:\DevSupport\Subversion\tools\backup\hot-backup.py D:\Repository\svn\Project D:\Repository\backup
 

After you run this, in the backup directory, you will see a new directory created having the same name and revision number as the project name and version it backed up. For example, you may get something like Project00-4 which means that this is revision 4 of Project00.

Restoring

The copy that is made is a copy of the entire repository and is actually a fully working repository and can be used just like any other repository. There is no special procedure to restore a backup.

Links

This topic has been written about quite a bit and you will find quite a bit if you search Google.

  • Refer to Repository Management in the ‘official’ SVN book for more details.
  • This article helped me get started (I just made minor modifications to get it working on Windows)
  • Finally, this article talks about the dump and load commands that can also be used for backing up, migrating and restoring repositories.

Mon Apr 30 18:25:00 UTC 2007

Running svnserve as a Windows Service

Posted in SubVersion at 06:25 PM by mohits

It took me a while to assemble this information about what needs to be done to run svnserve as a Windows service and since I shall need this information in another few days when I set it up on a different server, it made sense to link it here.

Background

svnserve allows you to connect remotely to an SVN repository over a network. In these cases, the repository names are something like “svn://server/project” and this is regarded as one of the easiest ways to connect over a network. This method is usually recommended for corporate LANs where you are confident that your communication is safe from snooping. There are other ways such as ssh + svn which can offer greater security, but I digress.

If you decide that svnserve will work for you and you have svn running on a Windows computer, then you may want to run it as a service. That way, it can be made to start up automatically when the computer restarts (as it will every now and then if it has just installed a bunch of updates automatically) and is generally easier to manage.

What needs to be done?

Basically, the latest svnserve already has everything that is needed to run it as a service. All you need to do is install it as service by passing it the correct options. Let’s assume that you have the following settings:
  • Subversion Installation: C:\DevSupport\Subversion
  • Repository: D:\Repository

If this is the case, you need to go to a Command Window (Start Key> Run> cmd [enter] >) and run the command SC.exe to interact with the service manager. You could type sc.exe to see how it works and what it expects from you.

For the impatient, this is what you need to type in at the command prompt to register svnserve as a service.

C:\>sc create svn_repos binpath= "C:\DevSupport\Subversion\bin\svnserve.exe --service --root D:\Repository" displayname= "Subversion Repository" depend= Tcpip


There a few things to note here:

  1. Options to sc create must have the equal-to sign stuck to the option name (it’s part of the option name) and there must be one space after it. So, depend= Tcpip is correct and depend = Tcpip, depend=Tcpip and depend =Tcpip are all wrong.
  2. The display name is what it will show up as in the Service Manager. You can set it to whatever you like.
  3. The binpath is the actual command line that will be called. Note that the option to run it as a service is --service and no other option works. It must be --service if it is to work.

Do I need one service for each repository?

In short, No. The command line option to svnserve only identifies a root directory which will be served up. The repository can be in any directory below it.

Suppose that your repository looks something like this:

D:\Repository
  |
  |- Project 1
  |
  |- Project 2
  |
  |- Project 3

and you use the above to serve it up, then the URLs for accessing the 3 projects from a Subversion client will be:

Project1 - svn://server/Project1
Project2 - svn://server/Project2
Project3 - svn://server/Project3

So, basically, if the individual project repositories are under the same root directory, you do not need a separate service. You will need a separate service for each root directory because I don’t think that a single svnserve service can handle multiple root directories.

How do I make it automatically start upon reboot?

The steps above will only ensure that the service is installed. If you want the service to start, you need to do a couple of other things.

  1. Go to the Service Manager (Start Button> Run> services.msc [enter])
  2. Find the service you just installed (if you called it Subversion Repository, then that will be the service name)
  3. Right-click on the name of the service and select properties.
  4. If the service is not running, start it by clicking on ‘Start’
  5. Change the start-up type to ‘Automatic’
  6. Click on ‘Apply’ or ‘OK’ and exit the page.

The service is now running and will be automatically started every time Windows is restarted.

Refer to this note for all the gory details.

Mon Apr 30 17:22:00 UTC 2007

svn:ignore for Visual Studio and Codegear Turbo C++

Posted in Codegear Builder | Turbo C++, SubVersion at 05:22 PM by mohits

I have just gone through setting up Subversion and was looking at which directories and files need to be ignored by the client when it uploads the project. I expect that I shall need to set these properties for every project that I work with, so I decided to put up the list here so that it’s easy to find it the next time I need it. If it helps you, that’s a bonus :)

If you are using TortoiseSVN, you can set these properties by right clicking on the name of your project sandbox directory and then following the TortoiseSVN>Properties. In the form that pops up, click on “Add” and for property name, select “svn:ignore” from the drop down list. Then, in the memo field, just copy and paste the set of files to ignore. Check “Apply property recursively” to apply it to all directories.

Visual Studio 2005

*.obj *.exe *.pdb *.ncb *.res *.pch *.idb

In addition, you can also ask it to ignore the directories in which it creates the executable code. Since I’m using Visual Studio for Windows Mobile development, this will usually be a directory such as “Pocket PC 2003 (ARMV4)” which will have files that are created during the build process. When you do your first “Commit” with these directories there, just right click on each of the directory names in the TortoiseSVN list and ask it to ignore it.

Turbo C++ Professional

*.obj *.~* *.dsk *.d *.local *.bcc32pch *.res *.tds *.exe *.bbc *.bbd *.bbl *.bbp

In addition, you can also ask it to ignore the directories in which it creates the executable code. Since I’m using Turbo C++ for Windows PC development, this will usually be a directory such as “Debug_build” and “Release_build” which will have files that are created during the build process. Also, you can ask it to ignore the “__history” directory if you don’t care about the revisions that Turbo C++ maintains. When you do your first “Commit” with these directories there, just right click on each of these directory names in the TortoiseSVN list and ask it to ignore it.

Sun Apr 15 14:44:00 UTC 2007

Announcing: TE@Onghu Developer Forum/ BBS (TEBBS)

Posted in T-Engine/ T-Kernel at 02:44 PM by mohits

TE@Onghu is proud to publicly announce the TE@Onghu Developer Forum/ BBS (TEBBS). The Developer Forum/ BBS is open to everyone and is a great place to ask questions about Embedded Systems, T-Engine/ T-Kernel Programming, Porting Issues, T-Engine Hardware or just about any related topic. New threads will be added in as necessary. You can use it to tap into the knowledge of experts across the world, or register and help newbies who are just getting started.

TEBBS has been in usability testing since February 2007 and currently has 16 members. There are almost 100 posts in more than 20 topics – already, some interesting topics have been discussed.

TEBBS is online at http://www.onghu.com/tebbs/

Anyone can browse through the TEBBS topics online. However, you will need to sign up to post new questions and to get access to other special features such as receiving notifications when queries of interest receive new posts. Also, there is an internal messaging system that you can use to contact other TEBBS members.

Register now to get started: http://onghu.com/tebbs/YaBB.pl?action=register

Mon Apr 09 17:47:00 UTC 2007

TE@Onghu T-Engine Information Festival

Posted in T-Engine/ T-Kernel at 05:47 PM by mohits

TE@Onghu (provider of T-Engine/ T-Kernel information in English) is now 2 years old. To celebrate 2 years of TE@Onghu and its supporting company (Viometrix), we have organized a special information festival online. From April 9th (today!), we will upload one new article on every working day for two weeks (a total of 10 new articles).

Also, on 15th April, we will be announcing a new feature of the TE@Onghu website that should be of great interest to other developers using the T-Engine, and will provide yet another source of support for the T-Engine community.

The festival is now online at http://www.onghu.com/te/ and the first article called “Future Directions with the T-Kernel” is already online at: http://www.onghu.com/te/html/future_directions_with_the_tke.html

Thu Mar 29 02:50:00 UTC 2007

Using Textile Editor Helper and acts_as_textiled

Posted in Ruby on Rails at 02:50 AM by mohits

One of the ways to allow lean markup for text is to use Textile for the text fields. Using acts_as_textiled can make this process even easier. The only thing that was missing was to have a way to allow users to enter Textile-formatted text with greater ease… until now, that is!

Enter the Textile Editor Helper to ease this step. This article just takes you step-by-step to show you how to get a Textile-enabled field working in your Rails app.

Install RedCloth if needed

To use Textile, you must install the RedCloth gem first.


1
2
3
4
5
6
rails_apps>gem install RedCloth
Attempting local installation of 'RedCloth'
Local gem file not found: RedCloth*.gem
Attempting remote installation of 'RedCloth'
Updating Gem source index for: http://gems.rubyforge.org
Successfully installed RedCloth-3.0.4

Create a new Rails app

I want to assume nothing, so I’ll just start from scratch here. Create a new Rails app by using the usual way.


1
2
3
4
rails_apps>rails ted_sample
      create
      create  app/controllers
      ... 

Create the database for it

Using whatever method you prefer, create a database (command line, phpMyAdmin, etc.) for the application. In my case, I added a database called ‘sample’ to MySQL running on my localhost.

Adjust the connection properties

Go to

rails_app\ted_sample\config
and edit
database.yml
to point to the actual database. I’m using development mode only (this application has a life of 10 minutes) and the database properties need to be set as above.


1
2
3
4
5
6
development:
  adapter: mysql
  database: sample
  username: <put db user name>
  password: <put password>
  host: localhost

Install the plugin – acts_as_textiled

You can get the details to install the

acts_as_textiled
plugin from the link above. But, it’s quite simple to do.


1
2
3
4
5
6
rails_apps\ted_sample>ruby script/plugin install svn://errtheblog.com/svn/plugins/acts_as_textiled
A    E:\InstantRails\rails_apps\ted_sample\vendor\plugins\acts_as_textiled
A    E:\InstantRails\rails_apps\ted_sample\vendor\plugins\acts_as_textiled\test
A    E:\InstantRails\rails_apps\ted_sample\vendor\plugins\acts_as_textiled\test\memory_test_fix.rb
A    E:\InstantRails\rails_apps\ted_sample\vendor\plugins\acts_as_textiled\test\setup_test.rb
...

That prepares you to do the first bit. But while we are at it, let’s also put in the Textile Editor Plugin, shall we?

Install the plugin – Textile Editor Helper

This one is equally simple. From the root directory of your Rails app, just run the following:


1
2
3
4
5
6
7
rails_apps\ted_sample>script/plugin install http://svn.webtest.wvu.edu/repos/rails/plugins/textile_editor_helper/
+ ./textile_editor_helper/MIT-LICENSE
+ ./textile_editor_helper/README
+ ./textile_editor_helper/Rakefile
+ ./textile_editor_helper/assets/images/textile-editor/background.png
+ ./textile_editor_helper/assets/images/textile-editor/blockquote.png
...

Now, run the install script for it.


1
2
3
4
5
6
7
rails_apps\ted_sample>rake textile_editor_helper:install
(in rails_apps/ted_sample)
 * Copying /assets/images/textile-editor/background.png       to /public/images/textile-editor/backg
round.png
 * Copying /assets/images/textile-editor/blockquote.png       to /public/images/textile-editor/block
quote.png
...

Create the first model

OK, from the root directory of your Rails application and generate the first model


1
2
3
4
5
6
7
8
9
rails_apps\ted_sample>ruby script\generate model item
      exists  app/models/
      exists  test/unit/
      exists  test/fixtures/
      create  app/models/item.rb
      create  test/unit/item_test.rb
      create  test/fixtures/items.yml
      create  db/migrate
      create  db/migrate/001_create_items.rb

Edit the migration file

The next step is to add in the details about the model into the migration file. Open up

db/migrate/001_create_items.rb
and modify it so it looks something like this.


1
2
3
4
5
6
7
8
9
10
11
12
class CreateItems < ActiveRecord::Migration
  def self.up
    create_table :items do |t|
      t.column :name, :string, :null => false
      t.column :descr, :text
    end
  end

  def self.down
    drop_table :items
  end
end

And apply the migration as always.


1
2
3
4
5
6
rails_apps\ted_sample>rake db:migrate
(in rails_apps/ted_sample)
== CreateItems: migrating =====================================================
-- create_table(:items)
   -> 0.0900s
== CreateItems: migrated (0.0900s) ============================================

OK, time to go to the application now and actually use the plugins.

Identify the field for Textiled data

Open your model file

apps\models\item.rb
in an editor and change it to something like the one shown below, marking
descr
as the textiled field.


1
2
3
class Item < ActiveRecord::Base
    acts_as_textiled :descr
end

Create the controller and view for the model

OK, I’m going to cheat here and just use a scaffold to get this done faster.


1
2
3
4
5
rails_apps\ted_sample>ruby script\generate scaffold item
      exists  app/controllers/
      exists  app/helpers/
      create  app/views/items
      ...

Include prototype.js

The Textile Editor Helper relies on

prototype.js
for some features. So, you need to ensure that it is included in the final page that is rendered. One of the easiest ways (for this sample) is to include it in the layout for the
item
class. Edit
ted_sample\app\views\layouts\items.rhtml
to include a call to
javascript_include_tag
in the header part of the file.


1
2
3
4
5
6
7
8
...
<head>
  <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
  <title>Items: <%= controller.action_name %></title>
  <%= stylesheet_link_tag 'scaffold' %>
  <%= javascript_include_tag 'prototype' %>
</head>
...

Modify the form to use the Textile Editor Helper

(This information is direct from the Textile Editor Helper website)

Navigate to the

app\views\items\_form.rhtml
so that we can add in the code for the helper.

Replace the text area tag with <%= textile_editor 'object', 'field' -%> This accepts the same options as the regular text area tag. Also, at the end of the form, put in the following code: <%= textile_editor_initialize -%>

Once this is done, the

app\views\items\_form.rhtml
file will look something like this.


1
2
3
4
5
6
7
8
9
10
11
<%= error_messages_for 'item' %>

<!--[form:item]-->
<p><label for="item_name">Name</label><br/>
<%= text_field 'item', 'name'  %></p>

<p><label for="item_descr">Descr</label><br/>
<%= textile_editor 'item', 'descr' -%>

<!--[eoform:item]-->
<%= textile_editor_initialize -%>

One small change

Since we are using the scaffold, it escapes all the data when it outputs it. What this means is that if you use it as it is, the textiled fields will display the actual HTML code rather than rendering it. So, we can change the show.rhtml and list.rhtml files to render the actual text. I’m changing just the

app/views/items/show.rhtml
file to the code below – you can change the other one if you want.


1
2
3
4
5
6
<p><b>Name:</b> <%=h @item.name %></p>
<p><b>Description:</b></p> 
<%= @item.descr %></p>

<%= link_to 'Edit', :action => 'edit', :id => @item %> |
<%= link_to 'Back', :action => 'list' %>

Start the Server


1
2
3
4
rails_apps\ted_sample>ruby script\server
=> Booting Mongrel (use 'script/server webrick' to force WEBrick)
=> Rails application starting on http://0.0.0.0:3000
...

Go to http://localhost:3000/items/ to see how it works.

Mon Mar 26 14:17:00 UTC 2007

Sending Email with Ruby

Posted in Ruby at 02:17 PM by mohits

I know that there are a number of guides online that provide the basic source for sending email using Ruby but I found that the basic sample code was lacking in one major respect – it did not set the date on the outgoing email. That meant that there was no specific “sent time” for the email and its treatment would depend on the email client. For example, Thunderbird would mark it with the date/ time at which it was downloaded.

The solution to this problem is really quite simple – you just need to format and print the date into the message as shown below.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
require 'net/smtp'

#Senders and Recipients
from_name = 'My Name'
from_mail = 'me@mydomain.com'
to_name = 'My Friend'
to_mail = 'them@theirdomain.com'

#Servers and Authentication
smtp_host   = 'mail.mydomain.com'
smtp_port   = 25
smtp_domain = 'mydomain.com'
smtp_user   = 'user@mydomain.com'
smtp_pwd    = 'secure_password'

#The subject and the message
t = Time.now
subj = 'Sending Email with Ruby'
msg_body = "Check out the instructions on how to send mail using Ruby.\n"

#The date/time should look something like: Thu, 03 Jan 2006 12:33:22 -0700
msg_date = t.strftime("%a, %d %b %Y %H:%M:%S +0800")

#Compose the message for the email
msg = <<END_OF_MESSAGE
Date: #{msg_date}
From: #{from_name} <#{from_mail}>
To: #{to_name} <#{to_mail}>
Subject: #{subj}
  
#{msg_body}
END_OF_MESSAGE

Net::SMTP.start(smtp_host, smtp_port, smtp_domain, smtp_user, smtp_pwd, :plain) do |smtp|
  smtp.send_message msg, smtp_user, to_mail
end

And that’s all there is to it!

TODO: Need to make the time printing more generic – right now, it’s kinda hard-coded to my time zone.