ephekt Programming seems to be my existence

6Feb/100

Facebook Application: Hello Birthday

About a month ago it was my birthday. On that day I was receiving countless e-mails from Facebook notifying me of Happy Birthday messages when I realized many of the messages followed a particular pattern (i.e. "Happy Birthday(!| <name>,| <endearing term>). Don't get me wrong, I enjoy and appreciate all of my birthday wishes. But being an Engineer, my brain finds patterns and attempts to "code up solutions." However, I had not played with the Facebook API yet and had been waiting for a good reason to come around so I took the idea of a Happy Birthday messenger to work and put together a version one of my Hello Birthday application. The application follows a few goals: to be easy to understand, easy to use, and it should just work. With that, here are the criteria I came up with to take a crack at achieving these goals:

  1. Automatically message friends on their birthday
  2. Allow enabling and disabling of such said feature
  3. Use a generic message that more than 50% of users observed currently use when wishing a friend "Happy Birthday"
  4. Manage an exclusion list, containing the friends Hello Birthday should not automatically message
  5. Post onto the friends' wall as if it were the user

With plans to continue development, I have a more robust friend list module going in soon and the ability to set up custom messages for particular friends. Eventually, some form of gift giving may be in order. To bootstrap development I followed a few principles:

  1. Prototype over masterpiece
  2. Design impacts implementation, but implementation makes design possible
  3. Low budget: use open source and free resources

To prototype the project I chose to use Ruby on Rails and SVN. To bridge my rails application and Facebook, I added the Facebooker rails plugin to my application. Facebooker is a pretty neat extension to Rails that provides all kinds of helper methods and an extremely easy to use interface wrapping the Facebook API. It also provides nice view helpers for generating FBML (the Facebook Markup Language) and FBJS (Facebook JavaScript). Developing version one locally saved quite a bit of time by realizing change immediately as opposed to any form of deployment. I then set-up a Facebook application (in Sandbox mode) for development (i.e. hello_birthday_dev) that only I had access to. Facebook offers test developer accounts, so after registering 6 or 7 of these to use with tests I was able to enumerate all of the states that Hello Birthday would need to recognize and transition.

When it came time to deploy to production I needed a production server and Facebook application. I registered the Facebook application (again, in Sandbox mode) for production (i.e. hell0_birthday) and then signed up for hosting with Heroku.com. Heroku is a Ruby (mostly Rails) cloud computing platform as a service. Basically, you get one free "cpu worker" and as you need more they sell scalable features. This, however, is perfect for what I need: a Rails host that allows cron jobs and makes deployment super fast & easy. Sure enough, Heroku makes deploying an application as easy as:

  1. git add .
  2. git commit -a
  3. git push heroku master

A slug of my app is created and deployed to my birthday.heroku.com production server. And to make sure I can monitor errors, I installed the hoptoad error monitoring service. Hoptoad app provides me with web-based access to error reporting and resolution management (organizes errors based on environment; test, production, and or development).

The training wheels were taken off: Sandbox mode disabled on Hello Birthday. I submitted my application to the Facebook directory a week or so ago and it's been smooth sailing since. I currently am servicing a little over 40 people. No complaints have been submitted thus far.

In summary, this is my first Facebook application and I have tried to utilize a lot of the latest technology in the process to illustrate how quickly a scalable solution to an easy problem can be solved. With Heroku & fairly efficient code, I do not foresee a problem handling a potentially high growth rate. I will try to bring back updates to this article if anything goes terribly wrong.

You can check out the Facebook application at http://apps.facebook.com/hello_birthday

24Sep/090

AnswerWise — The power of humans

Over the last few weeks I have run into numerous spiders and being the inquisitive type of person I am I always want to know what I am looking at. Thanks to my senior capstone project at the University of California at Santa Barbara, I finally have an answer to pretty much any question I could formulate... And the best part about AnswerWise is that it supports images. Win win. Here is the latest question asked and it's answer. (AnswerWise had the answer in under 10 minutes)

What kind of spider is this and is it poisonous?

spider

Answer: This is a Phidippus johnsoni (Red-backed Jumping Spider) its bite results in swelling and pain at the bite site but its not poisonous. But of course if you are allergic it will be worse.

Pretty cool huh? I think so. A little bit about our senior project statistics: Over 800 questions have been asked with an average 15 minute response time and 80% or more of the asked questions include images.

Filed under: Information No Comments
30Aug/090

jQuery & Navigation: sliding sub navs

We've all seen those web sites that have navigation links that, when clicked, slide down a sub navigation. I recently put one together for thatwasmean.com and thought I would take a moment to clean up, generalize, and make easily viewable an example. You can find the working example in my examples directory, here.

To make this functionality possible I utilized jQuery's slideUp and slideDown functionality. This is a neat little function that changes the display property from displaying the full element to slowly hiding the top part of it until the whole element is hidden, at which point the display CSS attribute is set to none.

I am going to put the main parts of the example here in this point, but keep in mind you will have to set up the remaining html tags (like body and head) as well as include the jQuery framework. It is encouraged to view the working example to see some of the added styling to make things look a little prettier (since in this post scope I am only including the necessities)

Let's begin with the CSS styles to set things up. We have three sub navigation items and so we need to set those three sub nav items with a display property set to none. You will also note I have modified text alignment in here, since each sub nav requires different aligning. The 'flash_about' is the container for the navigation as well as the sub navigation items. This is easy to change if you wish, but I stuck it all in one place as it suited my needs.

#flash_about {
  text-align:right;
}
.sub_nav_box {
  font-weight: normal;
  padding:0.3em 1em 1em;
  border-top:1px dotted #C1CDCD;
}
#add_new_thing {
  display: none;
  text-align: left;
}
#about {
  display: none;
  text-align: left;
}
 
#browse_by {
  display: none;
  text-align: center;
}
#browse_by &gt; .link {
  margin-left: 0.2em;
}
.nav_link {
  margin-left: 1em;
}

Next we need our JavaScript... using the jQuery functions mentioned above and a little jQuery helper magic we have a toggle_div function that takes a div ID and will toggle that div. This function is cool in the sense that it will hide all other opened sub nav items and only show the one you are selecting. Further, if you click a navigation link and its corresponding sub navigation item is already being displayed then the function will slide up that sub navigation item. (The $ symbol represents a call to jQuery.)

function toggle_div(div_id) {
  var div = $('#'+div_id);
  var divs = $('#flash_about').children('div').not(div);
 
  if(div.css('display') == 'none')
  {
    divs.slideUp(function() {
      div.slideDown();
    });
  }
  else
  {
    div.slideUp();
  }
}

Lastly, let's get the HTML in here to make all of this mean something to the viewer. I have left some content in the sub navigation items to give the overall example some meaning. (I strongly dislike examples where everything is named 'example 1, example 2, examples 3-- show me some content good sir!)

<div id="flash_about">
 
  <a class="nav_link" onclick="return toggle_div('about');" href="#">About</a>
  <a class="nav_link" onclick="return toggle_div('browse_by');" href="#">Categories</a>
  <a class="nav_link" onclick="return toggle_div('add_new_thing');" href="#">Submit something</a>
<div id="add_new_thing" class="sub_nav_box">
<div style="margin-bottom: 0.4em; margin-top: 0.4em;">
      <span id="add_new_thing_title" style="color: #333; font-size: 16px;">Type your thing here... </span></div>
<textarea id="add_new_thing_body" class="thing_input" style="border: 2px solid #666;" cols="40" rows="10"></textarea>
<div id="new_thing_buttons">
      <a class="button" href="#">add new thing</a> or <a onclick="toggle_div('add_new_thing');" href="#">cancel</a></div>
</div>
<div id="about" class="sub_nav_box">
    Welcome to my web site. This is the about us... it is awesome. Feel free to browse the site and check out some of our cool features.</div>
<div id="browse_by" class="sub_nav_box">
    <a class="link" href="#">link</a>
    <a class="link" href="#">link</a>
    <a class="link" href="#">link</a>
    <a class="link" href="#">link</a>
 
    <a class="link" href="#">link</a>
    <a class="link" href="#">link</a>
    <a class="link" href="#">link</a></div>
</div>

And there we have it. Go check out the example to see it in action. I hope you enjoyed this post. If you have any requests on JavaScript/jQuery examples let me know... As I find more time I will put up more examples of common uses of JS & jQuery.

29Aug/090

Show/Hide ToolTips with jQuery (revisited)

Finally, I got around to putting together a very simple demonstration (no graphics or styling) of using jQuery to show and hide (toggle) tool tips. I have put together I demo you can access at examples/jquery/show_hide_tooltips_ex1. Ctrl+U to view source.

What I have put together in this demonstration:

  • an on ready document function that tells jQuery when the web page has rendered to become active
  • a binded click event on all input boxes with a class named 'form_field' that will call back a function when clicked
  • a call back function that will hide all other tooltips and display the one corresponding to the input box clicked

Here is the source code to view. Again, to see it functioning go to the above link! And don't forget for all of this to function you must include the jQuery JavaScript framework into your <head></head> html page. You can link or grab a copy from Google Code (here), and the version I am using is jquery-1.3.2.min.js.

$('.form_field').bind("click",
    function()
    {
      var divs = $('.tooltip_example1');
      var field = this.id;
      var div = $('.tooltip_example1[id='+field+']');
 
      if(div.css('display') == 'none')
      {
        divs.hide(function()
        {
          div.show();
        });
      }
      else
      {
        div.hide();
      }
    });
  });

And within the body of your html page you should add the following html

<table border="0">
<tbody>
<tr>
<td>
          Username</td>
<td>
<input id="username" class="form_field" size="30" type="text" /></td>
<td>
<div id="username" class="tooltip_example1" style="display:none">
          This is how we'll identify you</div></td>
</tr>
<tr>
<td>Password</td>
<td>
<input id="password" class="form_field" size="30" type="text" /></td>
<td>
<div id="password" class="tooltip_example1" style="display:none">
           And how you keep it safe</div></td>
</tr>
<tr>
<td colspan="3">
<input type="button" value="Submit" /></td>
</tr>
</tbody></table>

The value in this kind of toggling is as a user goes through a form they can see suggested messages by you, the web developer.

19Aug/090

That Was Mean

For the past few weeks I have been spending a few minutes here and there putting together a catalog web site. Now, you may be asking what kind of catalog system would Mike be working on? Let me fill you in....

It all started with a co-worker, an awesome guy, and a few tasteful jokes. One bad joke later I wanted to get him back in a way that no man can deny: publishing a public wronging on the Internet. And, with that, thatwasmean was born.

It started as a very simple logging of things said in the office.

The categories grew for different needs.

The color schemes changes as suggestions came in.

But what I have found most interesting so far is the cohesiveness between posts. They relate to each other, even spread across multiple days, and you can generally figure out what goes with what and the livelihood of that incident within our office.

So, with all that said, ThatWasMean.com launches to a little more of a public scale. It was developed in Ruby on Rails, hosted using Phusion Passenger and Apache, and is evolving slowly... Check it out and provide any feedback.

go to ThatWasMean

14Aug/090

Ruby Regular Expressions – Security Risk

This post is a half reminder to elaborate when I have free time... But in short, there is nothing wrong with Ruby regular expressions, except that they behave differently than one might expect (in general and if coming from Perl RegEx).

Here is the dealy, from the Programming Ruby book by Dave Thomas:

The patterns ^ and $ match the beginning and end of a line, respectively. These are often
used to anchor a pattern match: for example, /^option/ matches the word option only if it
appears at the start of a line. The sequence \A matches the beginning of a string, and \z and
\Z match the end of a string.

All sounds good right? Well, it turns out that Ruby will execute code within a regular expression if you can pass multi-line input to the parser. For example... Given

class EmailAttachment < ActiveRecord::Base
validates_format_of :attachment, :with => /^[\w\.\-\+]+$/
end

You can easily pass in

attachment.txt%0A<script>alert('open_sesame')</script>

which is converted (as %0A is a URL encoded new line), by ROR, into

"attachment.txt\n<script>alert('open_sesame')</script>"

You can think about the implications of this, feel free... I have been able to have some fun with my own personal site and getting arbitrary JavaScript and (worse) shell commands to execute. Also, I believe this may cause a larger security whole within routes for Rails (at least 2.1.0). I'll investigate this more later, as the beginning of this post says.

25Jul/090

Validating Emails in Ruby on Rails

It's time to validate e-mail addresses and you're sitting in a Ruby on Rails application. Fortunately, there are a few methods to tackle such a task, and a combination of them can yield a pretty nice solution.

The first idea is to use some lengthy regular expressions. But why enumerate/describe in regular expressions what we are looking for when TMail has it built in... Using TMail, it is possible to let our Ruby Net SMTP wrapper class parse the email address and decide if it is correct or not.

The second task is to make up for some of TMail's odd shortcomings: the fact that the text "bob" passes as valid for TMail is alarming, but throwing in some simple regular expression to get past this provides a pretty solid solution. (For the curious, "bob" is a valid e-mail to TMail because you could be sending messages to the local domain.)

First, here is our regular expression for a basic e-mail address...

/^([^@\s'"]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i

Next, we create a TMail object with our e-mail address...

tmail = TMail::Address.parse(address.to_s) rescue nil

I am rescuing nil here. You can rescue whatever error message you want, but for example sake I am not so concerned if the TMail fails to parse the e-mail address. You can pass in a multitude of e-mail formats and TMail will do its best to match the RFC standard for e-mail addresses.

You now have access to a TMail object with a flurry of options (TMail & documentation). Let's proceed.

My simply method calls TMail and then follows it with the regular expression match to ensure this e-mail address in question is ready to be used on the web. Here is my final result to a pretty safe-proof (so far, tested on a rather large web site) e-mail handler. This method will return the TMail object.

def validate_email e-mail
  tmail = TMail::Address.parse(address.to_s) rescue nil
  tmail if tmail.address =~ /^([^@\s'"]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
end

And for those of you who want the extra step, I have attached a helper method that takes a TMail object and gives you back the e-mail address in string format fully qualified.

def formatted_email tmail
  if !email.blank?
    friendly_name = (tmail.name.blank? ? "" : tmail.name.blank?).tr('"',"'")
    quote = '"' if friendly_name =~ /[&lt;,@;]/
    "#{quote}#{friendly_name}#{quote} &lt;#{address}&gt;"
  end
end

As always, test this code and do not trust it blindly. I could have fat fingered something...

25Jul/092

Google Mail Conversation Threading, and how to prevent

Tired of Google mail taking your e-mail and matching it to a gmail conversation incorrectly? Google mail has many cool features, one of which is the e-mail conversation thread view. This view shows e-mails matched based on subject, time, and correspondence grouped together to see a chronological conversation. While this is a neat feature that has made Gmail unique for so long, it can become cumbersome to companies and web developers as they try to ship out monthly statements, e-mail notices, or any other e-mail that for some reason has the same subject every time it is sent out.

The question I asked was: Is it sufficient to change the subject text every time I send out an e-mail?

The answer was no. The reason(s) were simple: the e-mail may need the same subject and/or you may not want to send your customer an e-mail with a unique character sequence in it that the user can see and potentially become confused about.

The solution: Follow suit with another cool feature Google mail has made apparent, the use of virtual inboxing. Add a short web-friendly unique code to your e-mail address username, appending with a + sign.

ephekt@gmail.com becomes ephekt+nM2eY@gmail.com

The key to this is that you should have a friendly name on your e-mail so that the recipient does not see the difference in e-mail addresses. Thus, with slight modification we now arrive at:

Mike R <ephekt@gmail.com> becomes Mike R <ephekt+nM2eY@gmail.com>

And to the end user all is sane. There are a few ways to generate unique tokens... In a Ruby on Rails project I used the built-in base 64 encoder, passing in a random number up to 3 characters long so that my generated code would not only be highly unique but relatively short.

def friendly_email_token
  ActiveSupport::Base64.encode64(rand(0x10000).to_s).tr("/+","_.").gsub(/=*\n/,"")
end

Just throw the above method into one of your classes and then you can define a method that appends this friendly_email_token to your e-mail address.

def randomize_address email
  unless email.blank?
    username, domain = email.split("@", 2)
    "#{username}+{friendly_email_token}@#{domain}"
  end
end

And voila! We're good to go. Call the randomize_address method with your e-mail (with or without a friendly name) and it will do the work.

28Mar/090

Unlimited + 50… In math class we were taught to ignore the constant

I was browsing the Internet, or as I like to call it the "InterWeb," and I found an interesting marketing ploy for shared web hosting. A company, which will remain nameless for legal reasons, advertises unlimited shared web hosting for the cheap price of about 6 US dollars per month if you purchase for 10 years in advance. What a deal right? Well, to further this awesome deal they felt the need to add 50 gigabytes of data to the already unlimited gigabytes of storage space that is included in the single package they offer customers. Interesting I thought. Does this kind of marketing strategy work? Who are these companies marketing to who think that their valued customers, and potential customers, do not understand that infinite is the greatest non-specific number attainable in math... And more importantly, why is the 50 GB of extra space the selling point? I laugh... But think it probably works; which is sad.

23Feb/090

An unexplained data loss & what’s up

At some point over the past week the hosting company I use had a 'hard drive issue' and unfortunately had to revert all hosting accounts to data from around December 2nd, 2008... Yes, the last back up they had was over 2 months old. Not only is it unsettling that they had such _old_ back ups of their clients software, but I have checked my e-mail history and see no communication from them letting me know that I had lost all of the last two months of progress and data. Upon logging into my client control panel I noticed a 6 month credit for hosting -- does this somehow make it okay for 2 months of work flushed away? No. In fact, I'd rather have those two months of work back. Luckily, I back up the important things every now and then. Still, the urking continues as I see in my e-mail inbox news from the hosting company to do data migrations to new 'more powerful' servers. Let me ask this: Will the power of these servers keep the hard drives from having 'issues'....... Issues are bad m'kay.

If you noticed down time or old content it has now been fixed and I apologize for the potential 'content not found' messages that awaited viewers access attempts.

As of lately, however, I have been doing something pretty neat: teaching a Ruby on Rails workshop on my college campus to students. I wanted to try introducing web framework technology + newly popularized programming languages so naturally Ruby on Rails was a perfect fit. I've now constructed 2 workshops, each lasting roughly 6 hours, and have had extremely high interest and attention spans from students. In the coming week I will be having at least 3 workshops and they take place on weekends. I'll be writing up information about that soon, so if you are interested in learning Ruby on Rails and are local Santa Barbara, CA I encourage you to attend. If you don't even know what Santa Barbara is I still encourage you to learn more by checking out the presentation I will be posting in the following weeks. (Expressing interest in this presentation will speed up how quickly I post it...)