Archive for March, 2009

Wildcard VirtualHost with Apache2

Posted 29 Mar 2009 — by admin
Category Programming

Set your ServerAlias directive to *.domain.tld – Here is a quick example.

<VirtualHost>
  ServerName example.com
  ServerAlias *.example.com
  DocumentRoot /var/www/path/to/site
</VirtualHost>

Now everything.example.com and anything.example.com, even though you didn’t explicitly set them, will map to the /var/www/path/to/site directory on the filesystem. The wildcard character “*” matches any string.

You’ll also need to set up a wildcard DNS “A” record. An “A” record, short for address, maps a subdomain to an IP address. If your running your own DNS, such as BIND, I assume you can handle this part on your own. If you use a hosted DNS provider like register.com or namebargain.com, you can make an A record through an admin control panel.

Ruby strftime() method arguments

Posted 29 Mar 2009 — by admin
Category Programming, Ruby on Rails

Just for reference strftime() arguments in ruby. Usage Time.now.strftime(“%B/%d/%Y”). Got this from http://snippets.dzone.com/tag/strftime

%a  weekday name.
%A  weekday name (full).
%b  month name.
%B  month name (full).
%c  date and time (locale)
%d  day of month [01,31].
%H  hour [00,23].
%I  hour [01,12].
%j  day of year [001,366].
%m  month [01,12].
%M  minute [00,59].
%p  AM or PM
%S  Second [00,61]
%U  week of year (Sunday)[00,53].
w  weekday [0(Sunday),6].
W  week of year (Monday)[00,53].
x  date (locale).
%X  time (locale).
%y  year [00,99].
%Y  year [2000].
%Z  timezone name.

Namespacing in Rails

Posted 27 Mar 2009 — by admin
Category Ruby on Rails

With namespace routes in Rails you can easily create a prefix for select resources. For instance, if you have an admin area or an account dashboard you can give logged in users access to methods that are not otherwise available. To use namespaces define them in config/routes.rb. *Note: this is available for the latest release of Rails, at this time it is 2.3.0. I think it’s supported back until Rails 2.0, but haven’t tested it.

In your config/routes.rb file

map.namespace :dashboard do |dashboard|
    dashboard.resources :properties, :collection=>{:available => :get}
end

This namespace will create routes such as dashboard/properties, dashboard/properties/1, essentially all the CRUD paths as well as a collection method “available” dashboard/properties/available. These routes can be accessed in your views with methods such as new_dashboard_property_path, available_dashboard_properties_path  etc. If your property model has it’s own controller that isn’t namespaced, properties_controller.rb, remember to modify the property form_for method to tell it to use the dashboard namespace. The normal form_for(@property), method takes just your property object. Instead pass the dashboard symbol inside of an array  to form_for

<% form_for [:dashboard, @property] do |f| %><% end %>

You can easily see all of the available paths from the command line using rake routes. I use grep to filter the results for conveinence, because on a large application I don’t necessarily need to see all the routes if I’m working just within a single namespace. rake routes | grep dashboard

Using Prototype to Access Form Data

Posted 26 Mar 2009 — by admin
Category Programming

Prototype has a powerful API for accessing and manipulating the Document Object Model, A.K.A the DOM. The following code will let you interact with a simple web form.

Suppose we have a form that contains hidden/or locked inputs and they need to be updated dynamically. If the user changes a select field or if a checkbox is de/selected, other values in the form need updating. This could be required when products have options and associated price points. If you want to offer the user the option to switch options without refreshing or navigation this is a simple and effective approach.

… Sample form…

<input type="hidden" name="option_plan_id" id="option_plan_id" value="1"><br/>
<input type="hidden" name="amount" value="150" id="amount">

<select name="select-plan" id="select-plan">
<option value="1, 150">
USD 150 - 1 person
</option>
<option value="2, 200">
USD 200 - 2 people
</option>
</select>

In this example I want to update the values on the amount and option_plan_id input fields. The first thing I need to make sure of is that the page has fully loaded. I’ll make sure that my code executes in this context by placing it inside the document.observe method. I’ll then set up an observer on my select field and if it changes, make assignments. Now, in this example, I just saved the plan id and amount information as a string. In my javascript code I split apart the string and then make the assignments. There are other, probably better, ways of doing this. For instance you could store serialized data/json, and then work with it inside your event. This seems simple enough, however, you’ll have to pay attention in the future, if your storage format changes! Here is the sample Prototype javascript code

<script type="text/javascript" charset="utf-8">
document.observe("dom:loaded", function(){ //when dom is fully loaded do -
//update fields when option is selected
Event.observe('select-plan', 'change', function(event){
var data = this.getValue();
var plan = data.split(",").first(); //breaks apart by comma
var amount = data.split(",").last();
$('plan_option_id').setAttribute('value', plan);
$('amount').setAttribute('value', amount);
});
});
</script>

Thats it for now!

Parse for Links with Prototype JS

Posted 25 Mar 2009 — by admin
Category Programming

Parsing for links with the Prototype javascript library is easy. Here is the pattern for finding links

/(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^
=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/

And to implement it you can loop through your containers that might contain links

document.observe("dom:loaded", function(){
var posts = $$("div#posts");
for(var i = 0; i < posts.length; i++){
var link_regex = /(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^
=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/;
var parsed_string = posts[i].innerHTML.gsub(link_regex, '<a href="#{0}"
target="_blank">#{0}</a>');
posts[i].innerHTML = parsed_string;
}
});

Add Users to a Group on Ubuntu

Posted 25 Mar 2009 — by admin
Category Programming

To create a new user on Ubuntu (Heron8)

adduser johndoe

To create a new group

groupadd barleyfarmers

Add johndoe to the barleyfarmers group

adduser johndoe barleyfarmers

The adduser command, when you’re first adding the new user account, will prompt you for information pertaining to the account -name, phone, password, etc. If you want to change the password use the passwd command followed by the username for that account.

passwd johndoe

using screen

Posted 23 Mar 2009 — by admin
Category Programming

Use screen when you want to manage multiple sessions in a terminal. Install it on Ubuntu

sudo apt-get install screen

There are a lot of options for screen. I won’t go into them. I use screen most often when I shell into a remote server and want to hop into my database, or parse a log file, run top and need to run another process at the same time. Instead of opening another terminal session, I just use screen and bypass login/sudo or whatever other options I have configured for my current terminal session.

Start up screen:

screen

Create a new screen session

ctl+a+c

Tab between your screen sessions:

ctl+a+n

There is a whole lot more to screen, like assignment of sessions to other users and groups.

paypal ipn simulator

Posted 22 Mar 2009 — by admin
Category Business

If you use the Paypal sandbox you’ll notice that there is an IPN Simulator test tool. You must be logged to use it. This tool lets you test an IPN handler script for your application. If your script is not correct and you try to send a test IPN transaction the simulator will spit out a misleading error message. It will report

IPN delivery failed. Unable to connect to the specified URL. Please verify the URL and try again.

What this actually means is that your server was contacted and your script failed! If you’re using the wrong URL then this error message will apply, however. If you are using the right URL but you have a handler script that fails or is not right in some fashion, it seems logical to report the details of the failure! At the very least, it would be nice to hear

Indeed this URL address is correct, we said hello, but you refused our ‘handshake’. How rude! Link to more info…

When I first tried out the simulator I assumed that the problem was with my DNS. I was testing against a subdomain that didn’t have a cname set up. I wasn’t too sure though if this was the problem. I could visit the URL I specified in my web browser and ping my domain, etc. I eventually got it working after checking some log files. I had to parse my apache logs to fnd that the IPN parameters were indeed posted to my server. This led me to the error in my code.

I’m not blaming Paypal 100%. The error was ultimately on my end. Nonetheless, Paypal did not aid in my troubleshooting endeavor. Instead they exacerbated the problem with an error message that made some assumptions about how I was using their tool. The first being that I understood the IPN protocol. The second, that I understood the way the IPN simulator is meant to work and the protocol under which it operates. Not my error because there is no documentation for the test tool.

Having to parse log files was a needless step in this otherwise simple remote request. Another issue that confounded the problem were the Paypal forums. Some people seemed to think that the IPN simulator was not even operational. Could this be because of misleading error messages?

In my opinion the Paypal documentation is thorough, however, very poorly organized. It seems also that a lot of the Paypal core docs are available in multiple/too many places. I’ve seen the IPN documentation in at least 3 or 4 different areas on the site. Each page adds more information or has a slightly different verbiage to explain the same problem.  Not to mention, there are way too many PDFs available for download! PDFs are great, but the content, organization and display is different from same documentation online.

At any rate, here is a quick Rails controller that will at least get your IPN simulated transactions to return success!

require 'uri'
require 'net/http'
require 'net/https'
class PaymentsController < ApplicationController
  #skip this check b/c post comes in from paypal
  protect_from_forgery :except => [:ipn]
  def ipn
    begin
      if request.post?

      #you need to post back to paypal the name/value string
      #in the same order received w/added cmd=_notify-validate
      from_pp = request.raw_post
      data = from_pp + "&cmd=_notify-validate"
      url = URI.parse 'https://sandbox.paypal.com/cgi-bin/webscr'
      http = Net:HTTP.new url.host, url.port
      http.use_ssl = true

     response, data = http.post url.path, data, {
        'Content-Type' => 'application/x-www-for-urlencoded' }
      end
     rescue Exception => e
     logger.info("Error: paypal transaction #{e.message}")
    end
  end
end

git checkout — file-in-question.oh-my

Posted 22 Mar 2009 — by admin
Category Programming

Problem: using git and one file, like your db/schema.rb, is out of whack with the latest branch. If you run git pull and you get a failed merge and no update. You can of course, edit the conflicts manually. But what if you’re confident that the latest schema.rb is correct? Instead of manually editing the file and doing all that work, you can grab the latest copy with the git checkout command.

Solution:  git checkout — <file>
… or for the Rails application example above…
git checkout — db/schema.rb

rails fixtures: using the right timestamp

Posted 21 Mar 2009 — by admin
Category Programming, Ruby on Rails

Fixtures in Rails allow you to quickly and easily populate a database with sample data. They are great when testing your app and you need to test against a condition that will rely on a certain preexisting data point.

Fixtures are located in your RAILS_ROOT/test/fixtures/model.yml where model.yml is the model in question.
A sample fixture *note: yml files require consistent indentation!

one:
  id: 1
  title: my sample fixture
  description: this is an example of a fixture
  created_at: <%= 2.days.from_now.to_s :db %>

You can load your fixture data like so

rake db:fixtures:load

This assumes that you have a schema migration already raked <code>rake db:migrate</code> and that the attributes in your fixtures map to the correct attributes in your schema. You’ll get an error otherwise. You can also specify the environment when you run your rakes like so…

rake db:fixtures:load RAILS_ENV="production"

As you may have noticed, you can execute Ruby code in your fixtures if you place your code in the normal erb tags
<%= %>. Furthermore, you have access to the Rails api, which gives you handy methods like 2.days.ago.to_s. When creating your fixtures you might be tempted to use <%= Time.now %> for you created_at, updated_at fields. Don’t! Instead, use the rails api like so… <%= 1.month.from_now.to_s :db %> This stores the value in the same way that Rails handles time stamping your models. Otherwise, you might find parts of your application break when running tests against your fixtures because the data types do not correspond.