Learning Ruby

2 February 2012 : code, php, rails, ruby, wordpress

Some seven years ago, I began life as a web programmer by learning PHP to build my first WordPress blog. Over the past twenty four hours I’ve embarked on my first project using a “new-to-me” programming language called Ruby on Rails. While I’ve been working my way through Michael Hartl’s Ruby on Rails Tutorial Book an upcoming presentation to a potential partner led me to just jump in and start buidling a prototype. Here’s a couple of things I’ve learned:

  • Rails is very different from PHP, yet somehow more elegant
  • Scaffolds are a great way to cheat as a programmer, but messy to clean up if you do something wrong
  • Don’t use a plural name for a model (i.e. “news”) because it will cause you a world of pain
  • Google as always is your friend but be sure to add the phrase “Rails 3″ to your searches
    • That said, there are answers to your questions out there, just be patient and try to find answers on stackoverflow. They truly are the best out there.

Anyways, I’ve been at this too long. Time to go home and get some sleep. More soon!


New Year, New Theme

2 January 2012 : code, new year, php, programming, wordpress

Today, I relaunched my blog design. As regular readers of this blog will note, I probably spend more time writing about reprogramming my blog than actually writing it. I’m hoping to change that in 2012 but allow me for a minute to discuss the story behind the latest incarnation of RasheqRahman.com.

The impetus began this past summer when Twitter announced its new CSS framework called Twitter bootstrap. As I read more about the theme and downloaded the v1.0 source code, the simple, clean design tugged at me as if begging me to use it in a project. I had looked for years for a simple theme that was mainly white for the text part but had a fixed top navigation bar that could pull together my different interests (photography, writing, web development) but in a compartmentalized way so that the output of each activity could be cleanly displayed in a format that highlighted its unique characteristics. Bootstrap provides such a lattice upon which build such websites. As always, WordPress is the brains behind this project because, like the dependable friend that it is, I can connect it to my front end HTML and CSS almost immediately and know that the key files will be in the right place and easily customizable.

I vowed for this project to use as few WordPress plugins as possible, relying more on code snippets and design patterns to customize my website so I truly understood what was “under the hood.” As I hope to share in coming posts in the code category, I did this in order to improve my PHP skills and to gain a better understanding of WordPress theming. Having now completed this site and several others this year I am excited to declare that I intend to “hand roll” my own themes from here on out, i.e. using only HTML templates and adding in the WordPress code myself. If you are at the point of having configured a few existing off the shelf WordPress sites yourself and are looking to really grow as a WordPress developer, I highly recommend the “roll your own” approach.

Overall the process took some four months, with a two month long break in the middle and several pauses in the middle while I thought about the design and how I wanted everything to fit together. I decided to launch it today to kick start the New Year knowing full well that both content and design need some continued tweaking.

Look for the aforementioned coding posts in the coming weeks and please feel free to comment below. I look forward to your thoughts and questions.


The G4 is Gone! Long Live the Macbook Pro!

6 April 2008 : featured, mac, php

Today, I sold my old Powerbook G4 to someone else, bringing to the end my first Mac laptop in the modern (post Jobs’ return to Apple) era. This Mac was where I learned to program PHP and run MYSQL queries, where I first blogged and built my first production level website – www.nybap.org. It lasted for four and half years, much longer than I expected!

Fortunately, last week I purchased a new MacBook Pro 15 inch 2.4GHZ beast which will carry me forward!


I'm back and now in WordPress 2.0.2

26 April 2006 : bangladesh, featured, general, php

Hi. If you are a regular reader or spammer of this blog you’ve may have noticed that the blog has been down for the past couple of days. This all started with a badly botched attempt to upgrade my blog from WordPress 1.5.2 to v.2.0.2. Within minutes of copying over the files per the upgrade instructions, I was getting the dreaded “white screen of death” in php when I tried to load my home page. For the past days I’ve been working with the good folks at Textdrive, posting on their forums, but with no luck.

However this morning, I retraced my steps a little bit and with the help of the WordPress forums and Google, I was able to piece together a hack for my wp-config.php. I’m still not sure why this works but the hack turns off magic_quotes_gpc and disables the WordPress cache. I hope if any WordPress gurus are reading they will comment and shed some light on what these hacks do. Nonetheless, my site is up and running again, so please visit once more.

Now I have to get on to writing something worth reading …


Thanks Tod!

31 May 2005 : bangladesh, featured, php

Tod Maffin wrote about my OPML project for on his blog, iloveradio.org. Let’s see how long it takes to for Tod’s entry to be the top item when you google “rasheq rahman”

(As of this writing, his original post is #10 on the results page.)


My fifteen minutes of fame (or how to get OPML into HTML)

26 May 2005 : opml, php

A few days back as I was skimming through my plethora of rss feeds on Bloglines I came across a post from Tod Maffin looking for a programmer to write a simple script which would parse an OPML file of podcasts into HTML which could be included in a web page. The task was straightforward enough and given the ubiquity of OPML in RSS readers, I knew someone else would have at least written a basic parser in PHP that I could start with. I wrote back to Tod telling him that I was the man for the job and set about working on the script. I offered to do the script pro-bono as a way to help spread the word about public-radio podcasts which keep me entertained and amused throughout the day.

A quick google search brought me to Joe Grossberg’s PHP script for including his OPML Bloglines subscription list as an HTML un-ordered list on his blog. His code was very straightforward and well writen so I decided to use it as a base.

My first task was to strip out all the code that was particular to Bloglines OPML format and customize the script to the format of Tod’s OPML file (you can find an example here). This proved to be more difficult than I originally anticipated and I had to consult the PHP manual to understand how the PHP function, xml_parse_into_struct function worked in order to make sure I was pulling out the parsed podcast feed title and URL. However, after a few hours of trial and error, I was able to parse the OPML file correctly into an ordered list. I even added a small bit of code to ignore the first entry in his OPML file which is a link to add new podcasts. (Tod had hardcoded that link into his website and he only provided the link in the OPML file so that it could be used in the Ipodder directory to have podcast listeners contact him about new podcasts).

With the parsing complete, I turned to the task of displaying the podcast information in an HTML table. I took my cue from Tod’s orginial page which he had been manually updating as new podcasts were added. In that layout, podcasts were organized by categories and alternating categories had the same color so that it was easy to distinguish between categories. I wanted my script to generate the table entirely using PHP so I had to reaquaint myself with the process of writing code by hand because my script would have to add the table tags dynamically depending on how many podcasts were in the OPML file. After a few hours of tweaking the code and a night’s worth of sleep I finally had it generate a basic table which I could include in another PHP file.

In order to make the table a little easier to read, I used the trick of alternating colors for table rows that’s become popular around the Net and in applications like Apple’s iTunes. The easiest way I found to do this was to keep track of the number of podcasts in each category. Every time my script would go to write out the table cell definition for a podcast it would check to see if the podcast number was divisible by two meaning that it was even. Even numbered podcasts would be colored using one color and odd numbered podcasts would use a different color. To make things even more interesting, I kept track of the category number as well and wrote code to create two sets of even/odd color pairs – one for even numbered categories and other for odd-numbered categories. You can admire the results at http://todmaffin.com/feeds/ . http://publicradiofeeds.com.

With Tod’s permission I’m releasing the source code for my file under GPL so that others might benefit and improve on it. The file is called ipodder.opml.class.php. To use it, you’ll need to add the following code snippet as a table row in another .php file:

Anyways here is the link to the ipodder.opml.html.php.

I hope you find it useful in and of itself or as a point of departure for building your own OPML parser. Please email me with any feedback you might have at projects@rasheqrahman.com.


Ipodder Opml Class

25 May 2005 : code, opml, php, podcast, programming

<?php

/*************************************************************************************
* ipodder.opml.class.php
* ---------
* Author: Rasheq Rahman (rasheq.rahman@gmail.com)
* Copyright: (c) 2005 Rasheq Rahman
* Release Version: 1.0.0
* Date Started: 2005/05/20

* ipodder.opml.class.php is a PHP class to convert an Ipodder (http://www.ipodder.org) OPML file into a simple HTML table that can be inserted into a web page. More complete documentation can be found at http://www.rasheqrahman.com/.
*
* The orginial code for this class was written by Joe Grossberg. See http://www.joegrossberg.com/archives/001966.html for details.
*
*************************************************************************************
*
*
* ipodder.opml.class.php is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This class is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ipodder.opml.class.php; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
************************************************************************************/

class OPMLtoHTML
{
  var $index;
  var $vals;
  var $html = '';
  
  /* Set the color scheme for alternating podcasts and alternating categories
In the ipodder hierarchy, podcasts are organized into categories. A category might have one, two, etc. podcasts. To make the tables easier to read, I have implemented logic that sets different color schemes for alternating categories and alternating podcasts. You can use Hexadecimal colors or CSS color names. A good list is provided by the W3 Consortium at http://www.w3schools.com/css/css_colornames.asp
*/
  
  var $oddcategory_oddpodcast_color = "#D1CEF2"; // ex: category #1, podcast #1
  var $oddcategory_evenpodcast_color = "#E3E1F7"; // ex: category #1, podcast #2
  var $evencategory_oddpodcast_color = "#D8EDAF"; //ex: category #2, podcast #1
  var $evencategory_evenpodcast_color = "#EEF7DD"; //ex: category #2, podcast #2
  


  function OPMLtoHTML ($file)
  {
    $this->parse_opml($file);
    $this->generate_table();
  }

  function parse_opml ($file)
  {
    $fp = fopen($file, 'r');
    if (!$fp) return;
    $xml = fread($fp, filesize($file));
    fclose($fp);

    $parser = xml_parser_create('');
    $status = xml_parse_into_struct($parser, $xml, $this->vals, $this->index);
    xml_parser_free($parser);
    if (!$status) return;

    return true;
  }

  function generate_table () // creates table from parsed OPML file
  {
    $expand = $this->vals[$this->index['EXPANSIONSTATE'][0]]['value'];
    $expand = array_flip(preg_split('/,\s*/', $expand));
    
    $category_count = 1; // counter to track category # for color formatting
    
    $count = 0; // Not sure what this is used for but it was in joe's original script

    foreach ($this->index['OUTLINE'] as $i)
    {
      $type = $this->vals[$i]['type'];
      if ($type == 'cdata' or $i < $this->index['BODY'][0])
        continue; //skips over header informaition in OMPL file
        
       // code below is optional. You can use it create "indents" in the final HTML output so that code is nicely formatted
       
      if (empty($first_depth))
        $first_depth = $this->vals[$i]['level'] - 1;

      $depth = $this->vals[$i]['level'] - $first_depth;
      $indent = str_repeat(' ', $depth);

// when the last podcast is reached in each category, an extra row is added to provide a buffer for the next category.

      if ($type == 'close')
      {
        $category_count++;
     
        $this->html .= "<tr>\n<td height=".'"20px"'."></td>\n<td></td></tr>\n";
        continue;
      }
      
      $count++;

/*
the text (podcast name or category name) and $feed (rss/xml feed for podcast as parsed from the OPML file
*/

      $text = htmlentities($this->vals[$i]['attributes']['TEXT']);
      $feed = htmlentities($this->vals[$i]['attributes']['URL']);

      
            
      if ($type == 'complete')
     
      {
/*
skip over the first entry which is just a link to add a new podcast to the category. This is hardcoded in HTML already.
*/
        if ( preg_match("/\bClick to add your show to this listing\b/i", $text, $match))
        {
        continue;
        }
        
/*
identifies whether a category # is even/odd and the podcast # is even/odd. Apply appropriate formatting based on class variables defined above.
*/

        if ($category_count % 2)
         ($podcast_count % 2) ? $bgcolor = $this->oddcategory_oddpodcast_color : $bgcolor = $this->oddcategory_evenpodcast_color;
        else
         ($podcast_count % 2) ? $bgcolor = $this->evencategory_oddpodcast_color : $bgcolor = $this->evencategory_evenpodcast_color;

//formatting for podcast feed

        if ($feed)
        {
         $this->html .= "<tr> \n";
         $this->html .= $indent . $indent . '<td width="50px" align="center" bgcolor ="'. $bgcolor. '"><a href="' . $feed . '"><img alt="Click to select feed" src="http://www.scripting.com/images/xmlIcon2.gif" border="0" height="14" width="36"></a></td>'."\n";
        
//formatting for podcast name/description

        if ($text)
          $this->html .= $indent . $indent . '<td width="650px" align="left" bgcolor="' . $bgcolor. '" cellpadding="3"><B>'. $text . '</B>';
          $podcast_count++;
          
        }
        $this->html .= "</td>\n</tr>\n";
      }
      
//formatting for category name

      if ($type == 'open') // This for the section headers
       {
        $this->html .= '<tr><td colspan="2"><h3 align="left"><b>'. $text . "</b></h3></td></tr>\n";
        $podcast_count = 1; // counter to track podcast # for color formatting
       }
    }
  }
}

?>


Code to determine the user’s offset from GMT

13 May 2005 : code, php


The joy of open source

8 May 2005 : open source, php

I was first drawn to open source by the promise of free software. Blogs I read and respected would suggest a GPL’d app which I would download, use and not think twice about as long they worked. Open source apps were like any other piece of software – the only difference was they didn’t cost me anything.

However, now that I’ve been learning PHP, I have begun to appreciate open source apps in a completely different way. For me, taking apart a PHP program, tracing functions and variables across different include files, has taught me more than any book about how to write proper PHP scripts. The fact that I can “look under the hood” to see how a program is constructed is fascinating and has inspired me to do some tinkering myself.

Scuttle, my bookmark manager has a great feature which allows you to mark a bookmark public or private. This is most often done when the bookmark is first added but can be amended later by editing the bookmark on another page. By default, new bookmarks are publicly viewable which means that you don’t have to log in to access them. This is great for most uses but for personal bookmarks I would have to either remember to set my bookmark to private when I first added or click on the edit link which would take me to a separate page where I would have access to edit all fields (URL, description, tags, etc) related to that bookmark. All I wanted was a simple link on the page which would allow me to mark something as private or public without having to edit the entire boomark record. However, I noticed that beside the “edit” link there was another link called “delete” which allowed me to directly delete a link without having to go to another page.

Harnessing the power of open source, I was able to learn that the delete function worked quite simply and elegantly by parsing a URL which contained the id number of the boomark to be deleted. This boomark id was used by a php script to construct a DELETE query in MYSQL which removed the bookmark from the list of visible bookmarks. Knowing that making my bookmarks private or public was just a matter of executing an UPDATE query to set the bookmark status to either (0) for public or (2) for private, I easily copied the php file used for the delete action and modified the SQL script to UPDATE instead of DELETE. In the main bookmarks file, I also added two links to the script that created the bookmarks list which would allow me to mark boomarks public or private. Voila !! Without having to put in a feature request to the author I was able to customize scuttle to suit my work style.

Simply put, that’s really cool …


The author speaks

18 April 2005 : code, php, programming

I wrote a few weeks ago about learning php. Well today I got stumped by a php problem so I took the brave step of contacting the author of my php book, Jason Gilmore, to see if he could shed some light on my problem. I was surprised to see an answer from him by the time I had finished dinner and he even dropped a nice comment on my blog.

For a beginner like me, it’s nice to know that great help is out there.