Brian Wigginton B-lib – Notes & Tutorials on Delicious Bytes of Technology

Gentoo Linux – Wallpapers

Posted on February 15, 2010

For those of you looking for my Gentoo Wallpapers, they can be found here.

Gentoo Minimalist Wallpaper

1440x900 - Click for More Sizes

Filed under: Linux No Comments

Magento Sidebar Categories

Posted on January 17, 2010

The following will display a list of categories in your store in your right sidebar.

Layout

Alter page.xml so that the default handle's right block contains the following:

<block type="catalog/navigation" name="category.listing" template="catalog/navigation/categories.phtml" />

My final right block looks as follows

<block type="core/text_list" name="right" as="right">
	<block type="catalog/navigation" name="featured" template="catalog/featured_random.phtml" />
	<block type="catalog/navigation" name="category.listing" template="catalog/navigation/categories.phtml" />
</block>

Template

Create the file template/catalog/navigation/categories.phtml and paste in the following

<div class="block block-layered-nav">
  <div class="block-title">
    <h2>Categories</h2>
  </div>
  <div class="block-content">
    <ul id="nav_category" class="nav_category">
    	<?php foreach ($this->getStoreCategories(true) as $_category): ?>
    		<?php echo $this->drawItem($_category) ?>
    	<?php endforeach ?>
    </ul>
  </div>
</div>
Filed under: Magento, PHP 2 Comments

Magento Sidebar Featured Products

Posted on January 17, 2010

This tutorial will explain how to add a featured product to the sidebar. In this example we will add the featured product to the right sidebar. The steps we will follow are as follows.

  1. Create a new category in the magento admin area to contain our featured products.
  2. Add the block calls to the XML Layout
  3. Create the phtml template files to be referenced by the block

Category

Add a new category to your store to contain your featured products. Make it inactive and jot down the id that it is given once saved. Add any products you want to consider featured to this category. Also make sure this category is not a root category.

Layout

Open page.xml and inside your default handle's right block add the following line.

<block type="catalog/navigation" name="featured" template="catalog/featured_random.phtml" />

My finished right block looks as follows:

<block type="core/text_list" name="right" as="right">
	<block type="catalog/navigation" name="featured" template="catalog/featured_random.phtml" />
	<block type="catalog/navigation" name="category.listing" template="catalog/navigation/categories.phtml" />
</block>

Template

Use the following code for featured_random.phtml

<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE_AFL.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category   design_default
* @package    Mage
* @copyright  Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
* @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*/
?>
 
<?php 
$category_id = "25"; // category_id for "Featured Products"
$_productCollection = Mage::getResourceModel('catalog/product_collection')
  ->addAttributeToSelect(array('name', 'price', 'small_image'), 'inner')
  ->addCategoryFilter(Mage::getModel('catalog/category')->load($category_id));
?>
 
<?php if($_productCollection->count()): ?>
 
  <?php 
  $products = array();
  foreach ($_productCollection as $_product) { array_push($products, $_product); }
  $_product = $products[rand(0,count($products)-1)];
  ?>
<div class="block block-featured-product">
  <div class="block-title">
    <h2>Featured Product</h2>
  </div>
  <div class="block-content">
    <ul id="featured-product-list">
      <li class="featured-product">
          <h4><?php echo $this->htmlEscape($_product->getName())?></h4>
          <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>">
            <img class="product-image" src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(117, 117); ?>" alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" />
          </a>
          <a class="view-item-button" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>">View Item</a>
      </li>
    </ul>
  </div>
</div>
<?php endif; ?>

Resources:

Filed under: Magento, PHP 1 Comment

Pragmatic Development

Posted on January 14, 2010

What does it mean to be a pragmatic programmer, or to program pragmatically? Generally speaking, acting pragmatically or being pragmatic means to act practically. Taking things for what they are, don't make  things more difficult then they have to be. Take these ideals and apply them to development and you can be a very efficient, very productive, pragmatic programmer.

Andy Hunt and David Thomas have written a terrific book on Pragmatic Programming. They mention many qualities that they have found pragmatic programmers to possess:

  • A fast and early adopter - Pragmatic programmers love drinking the newest flavors of the technology coolaid. Playing with a new technology is like getting to play with a new toy. It's fun and represents something new and unknown to be figured out.
  • Curious and Inquisitive - Pragmatic programmers are always asking questions. Curious about how and why things work, and what the best way is to solve a problem. The knowledge picked up from these questions almost always becomes more useful in understanding future questions.
  • Grounded and Realistic - Pragmatic programmers have a very realistic view on things. They won't forget that the webapp you're building is only a tool for the means, not the end to the means.
  • Jack of all Trades - Being able to wear multiple hats makes pragmatic programmers more adaptable but also more valuable. Pragmatic Programmers have the ability to switch from one task to another pretty often, while still being able to claim a master or some.
  • Care about their craft - As a pragmatic programmer you have to care about what you are doing if you are to really have an appreciation for what you do. A pragmatic programmer has fun crafting their code and finding elegant, yet practical answers to their problems.
  • Always be thinking - A pragmatic programmer tries not to do things out of habit. Always asking "why?", and "how?" helps to always be thinking about your work and why you are doing it the way you are.

The Pragmatic Programmer

Image of The Pragmatic Programmer: From Journeyman to Master

Interviewing Your Future Employer

Posted on January 6, 2010

Going through an interview can be a rather daunting experience, however this is a good time for a candidate to find out more in depth information about the company, it's culture, processes and many other aspects that may not be immediately realized. This list should serve as a starting ground for job hunters looking to build a dialogue during their interview process.

I would first read through this list and break these up into categories that work for you. Save certain questions for round two or three, or for a more technical person, or for someone in more of a management role. It may be useful to ask some questions only once, or some towards each new intervewer you chat with to get a feel for how each role feels about a certain topic. Also, if you are fortunate to get the name of the person interviewing you, do your research on that person to build up some more topics to talk about during the interview. Finally, do your research on the company as well as demo their products/servces if you can and read through some source code they may have released to the Open Source world (you never know what sort of funny comments you might find that could spark a conversation).

Job Opening

  • What brought on the need for this opening, client? project?
  • What would be my title?
  • Who would I report to?
  • Were do I fit in on the company org chart?

Working Conditions

  • What kind of team will I be on?
  • How many people are on the team?
  • What skill sets the team members possess?
  • Take me through the day in the life of a developer.
  • How long is an average work day for a person in this position?
  • How often does the team have late night sessions to meet deadlines?
  • What sort of flexibility is allowed for work hours?
  • Can I work from home occasionally?
  • What sort of hardware is provided to developers? Multiple Monitors?
  • What is the usual expected productivity rate or utilization rate of your team?

Process

  • How are teams organized?
  • Explain the relationship between developers, creatives and account managers and how they work together on a project.
  • How is employee performance measured? By Whom?
  • Explain the lifecycle of a project from beginning to end and how each team is involved in each phase.
  • How does your team learn from there previous mistakes?
  • How does your team manage the tradeoff pyramid? Which point does the team continually find compromising on?
  • How are employees expected to track time? Using what software? To what accuracy?
  • How does the company share knowledge? (Is there a company wiki? Basecamp?)

Company

  • What are some difficulties the company is facing right now? What's the strategy in place to overcome those issues?
  • What's the toughest technical issue you are facing right now? Non-technical issue?
  • What is the companies policy on intellectual property?
  • What is the companies turnover rate?

Culture

  • Employee Age range?
  • What sort of extra curricular activities does the company provide? Are these organized by employees?
  • How often do departments get to mingle and meet one another?
  • What's the dress code?
  • Who was the last person you met for the first time at [COMPANY HERE]?
  • Where do most people live in the area?
  • Do people carpool?

Growth

  • What's the opportunity for growth within the company?
  • Where can I go? What can I do?
  • Does the company provide allowances for employee education? Conferences? Training? Workshops?
  • What is the company policy on being transferred to other offices?
  • Is there a mentorship program or something similar?

Development & Best Practices

  • Code Repositories? Which one?
  • How do you handle staging/development sites?
  • How do you handle bug reporting and testing? Is there a QA team?
  • How is a project schedule managed and maintained?
  • How is the office noise level?
  • How do people communicate around the office? Instant Messenger? Email? Twitter?
  • Is there a library available for developers?
  • Are there code reviews?
  • What Project Management tools are being used?
  • Does the team contribute code to the open source community?

Interviewer Specific

  • Should a developer be a jack of all trades or a deep specialist?
  • Why do you like working here? What are your favorite parts about your job? Least favorite parts?
  • How long have you worked at [COMPANY HERE]
  • What's something that you or your team has done that you are really proud of?
  • Where do you see me in 6 months?
  • What are you looking for in an ideal candidate?

Fun

  • Is your coffee filtered or unfiltered? Free?

I have assembled this list through various resources on the internet, Stack Overflow's - A Standard Set of Questions to ask and Interview as well as the infamous Joel Test by Joel Spolsky, friends and family. Thanks to all!

Please feel free to leave any additional questions or idea to the comments and I will try and add them to the list!

Subversion: Continuous Integration with a PHP Application

Posted on October 27, 2009

Abstract

This tutorial explains how to update a staging site whenever there is a commit to the SVN repository. This assumes basic knowledge of Subversion, Apache and C and that the staging site is running a working copy checked out from the repository.

Problem & Solution

When working close with designers or other non-coders it's often most productive to be able to make quick changes live to the box serving up the dev site, then to commit a change then update the server over and over. The bigger issue is that there is now modified code on the dev site that's not revisioned with subversion. To solve this problem we are going to update the codebase for the development site whenever anyone commits changes to the subversion repository.

update_svn

update_svn is a C program that will make a call to the svn command with our designated username and password and update the working copy. This program should live inside your applications directory.

update.c

#include <stddef.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
     execl("/usr/bin/svn", "svn", "update", "--username",
     "USERNAME", "--password", "PASSWORD",
     "/var/www/website/"(const char *) NULL);
     return(EXIT_FAILURE);
}

Compile and add permissions

gcc svn_update.c -o /var/www/website/update_svn
chmod +s update_svn

Subversion post-commit hook

In our subversion repository's post-commit script we want to add a call to update_svn. Add the following line to your post-commit script:

/var/www/website/update_svn

Resources:

Filed under: PHP, Subversion No Comments

Subversion: Repository on Subdomain

Posted on October 24, 2009

This is a tutorial on how to setup a Subversion repository on a subdomain with Apache. This assumes you have Subversion and Apache already installed on your system.

Subversion Setup

First you need to create a repository somewhere in your file system. Then grant apache permissions on that directory.

svnadmin create /var/svn/repository
sudo chown -R www-data:www-data /var/svn/repository

Controlling Access

Access to the repo via the web will be controlled by an htpasswd file located at /var/svn/svn-auth-file. Use the htpasswd command to create the file.

htpasswd -c /var/svn/svn-auth-file <username>

Execute the script again without the -c argument to add more people to the list.

htpasswd /var/svn/svn-auth-file <username_two>

Apache Setup

I usually setup Apache to use Names VirtualHosts to handle multiple websites. We'll make a new named virtualhost for subversion repository.

<VirtualHost *:80>
ServerName svn.your_domain.com
<location />
DAV svn
SVNPath /var/svn/repository

AuthType Basic
AuthName "Subversion repository"
AuthUserFile /var/svn/svn-auth-file
Require valid-user
</location>
</VirtualHost>

Subversion: Commit Emails

Posted on October 24, 2009

This is a tutorial on how to setup Subversion to email a team when there is a commit to the repository.

Subversion Hooks

Hooks are what Subversion executes upon certain events. Within your SVN directory you should see the following items

  • README.txt
  • conf
  • dav
  • db
  • format
  • hooks
  • locks

Go into the hooks directory and you will see a bunch of files ending in .tmpl. These are template scripts that are prebaked for you. Within each hook file are calls to scripts you want to be executed. To get one to execute you need to remove the .tmpl extension and then make it executable.

mv post-commit.tmpl post-commit
chmod +x post-commit

The Post Commit Hook & commit-email.pl

In post-commit there is a call to commit-email.pl. (Be sure that this calls to the absolute path of the script)

I didn't have commit-email.pl on my server but acquired it from the Subversion Tools Repository here.Save that file to your hooks directory. Also, be sure to edit that file and rename all the @SVN_BINDIR@ instances to the directory of you subversion executable. To find out type which svn and use the path that returns. Mine returned /usr/bin/svn to I used /usr/bin/ for @SVN_BINDIR@.

Run commit-email.pl without any arguments to see a list of options. To test this script point it to a repository and a revision number.

./commit-email.pl /var/svn/repository 1 --from "Subversion Gate Keeper <subversion@example.com>" youremail@example.com anotheremail@example.com

I like to prepend a subject line prefix so I can filter it a little easier when it comes through to my email client. Adding the -s argument to the command will allow you to specify a subject line prefix.

./commit-email.pl /var/svn/repository 1 --from "Subversion Gate Keeper <subversion@example.com>" -s "Commit Activity: " youremail@example.com anotheremail@example.com

Here are some more resources to help you out.

Edit - October, 27: You have to call your scripts within post-commit by their absolute path or else they wont run. Code above has been modified.

Tagged as: No Comments

Paperclip – Customizing Paths and URLs

Posted on October 19, 2009

To customize the paths and urls of paperclip objects in your rails app you need to modify both the :path and :url options for  has_attached_file in your models. Here's an example...

class SomeModel < ActiveRecord::Base
 
  has_attached_file :image_one,
    :path => "public/system/:class/:id/:filename",
    :url => "/system/:class/:id/:basename.:extension"
 
  has_attached_file :image_two,
    :path => "public/system/:class/:id/:filename",
    :url => "/system/:class/:id/:basename.:extension"
end


By default Paperclip will store your files in /system/:attachment/:id/:style/:filename. By passing the :path and :url options to the has_attached_file method in your model you can change where the uploaded files will be stored as well as where they can be accessed. The :path is the directory in your application where your files will be stored. The :url is the url that users will use to render the image.

Paperclip Resources

Tagged as: , No Comments

Ruby Script to Check Site Availability

Posted on October 7, 2008

Recently, I've been looking around for scripts to check the availability of websites I'm hosting, then email me a status message if there is anything I should be worrying about. There are many services out there, but none are free. Fortunately this kind of thing can be done with a little ruby script and cron job.

Requirements

  • SMTP server.
  • Ruby 1.8.6 - This script uses core classes of Ruby and doesn't require any rubygems
  • Ability to add cron jobs to your machine

Plan

Now, let's think out some solutions for how we can check on a site's availability. We could ping the server, but that only checks that the box is up and running. It doesn't necessarily mean that our HTTP Service is serving up pages correctly. We could use curl or wget to pull down the default page being served, but what if it's a holding space page, or a 404 error? This method would basically only tell us if the webserver is running or not, same as the ping method. Alternatively, we could test the to see what the response code of the page is. This way we can also find out what type of issue we are having on the server.

I also want this script to be a little more robust. Instead of having a hardcoded URL in my script,  I want it to pull a list of urls from a txt file. I also want each url report to be emailed to different email addresses since some of these sites are for work and some are personal.

Checking the Response Codes

There are lots of different response codes that we could receive from the server. The most familiar for anyone who's ever browsed the net is the infamous 404 Page Not Found error. Let's quickly take a look at what this error code means. Wikipedia states a 4** message means that "the request contains bad syntax or cannot be fulfilled.", in english, something went wrong on the web surfers side. This can be because of a mistyped URL or the result of a clicked link that took us to a page that's no longer available or has been moved. Now, the second two numbers tell us more specifically what kind of issue we've found, in our case *04, which Wikipedia explains as "The requested resource could not be found but may be available again in the future. Subsequent requests by the client are permissible." or in other words, it's lost, maybe only temporarily, but we can keep trying if we want.

Other response code groups include the following:

I'm not really interested in being notified of anything that starts with a 2**, since that means the site is up and functioning correctly. 3** are redirect codes, these might be useful, but I don't really care about them. I should know if one of my sites is being redirected because I would have had to set it up that way. I am only going to check if the response code starts with a 2xx or 3xx, if it does then were fine and I dont need to be notified. If it doesn't, then there's an issue and I need to know about it.

To check the reponse code of the page, Ruby has a class in it's core called Net:HTTPResponse, which will go out and touch a URL and return the reponse code the server supplied.

Sending the Email

This script uses the Ruby class Net::SMTP, which allows communication with an SMTP server. On my box I have postfix setup, which runs on port 25. When I send the email I want to be notified which url went down and what the response code is. I also added the HTTP version in there just in case.

Automatically Running the Script

To get this script to run automatically, I'm going to need to setup a cron job. To create a cron job we need to add a line to our crontab file, which can be found at /etc/crontab.

# [minutes] [hours] [day of month] [month] [day of week] [user] [command]
0,15,30,45 * * * * bawigga ~/scripts/check_uptime.rb

Above we can see that I set the script to run on the 0th, 15th, 30th, and 45th minute, of any (*) hour of any day of the month, of any month, of any day of the week, under the username bawigga, and we want to execute the check_uptime.rb script in my home/scripts directory.

The Script

#!/usr/bin/ruby
 
require 'net/http'
require 'net/smtp'
 
# Brian Wigginton
# http://www.bwigg.com/2008/10/ruby-script-to-check-site-availability/
# 10/7/2008
#
# Check's availabilty of a website. Needs to be run via a cron job.
# Example cron job line to be placed in crontab
#
# 0,15,30,45 * * * * username ~/scripts/check_uptime.rb
#
# This script uses a txt file to look for urls and email addresses.
# This text file needs to be in the following format
# -- lines with beginning with # signs will be ignored
# -- first thing should be the url
# -- then a space
# -- then email addresses seperated by commas, no white space.
# EXAMPLE
#       example.com admin@axample.com,bob@example.com
 
File.open("/home/user/scripts/sites.txt").each { |line|
	# get rid of CRLF
	line.chomp!
 
	next if(line[0..0] == '#' || line.empty?)
 
	url, emails = line.split(' ')
	emails = emails.split(",")
 
	# check if http:// was in the url if not add it in there
	url.insert(0, "http://") unless(url.match(/^http\:\/\//))
 
	# Get the HTTP_RESPONSE from the site we are checking
	res = Net::HTTP.get_response(URI.parse(url.to_s))
 
	# Check the response code and send an email if the code is bad
	unless(res.code =~ /2|3\d{2}/ ) then
		from = "admin@example.com"
		message = "From: admin@example.com\nSubject: #{url} Unavailable\n\n#{url} - #{res.code} - #{res.message}\nHTTP Version - #{res.http_version}\n\n"
		begin
			Net::SMTP.start('localhost',25 , 'example.com') do |smtp|
			smtp.send_message(message, from, emails)
		end
		rescue Exception => e
			print "Exception occured: " + e
		end
	end
}
Filed under: Ruby, Scripts 1 Comment