Easiest way to install / update Ruby on a Mac

The setup below was tested on a fresh install of OSX Lion, Ruby was updated from v1.8.7 to v1.9.3 and the standalone Command Line Developer Tools were used.

Yesterday, I started working on a project where I had to programmatically install / update Ruby on the local machine since the app I was making required it. Instead of just providing the link, I setup a basic helper, which downloaded and installed it for the user. Even before I began setting up the helper, I started looking at different implementations available for installing Ruby on a Mac and found several options. The biggest issue was the several dependancies each setup required (like Git), which meant installing several things before actually installing Ruby. The following is one with the least dependencies, i.e. 2 of them.

Step 1: Install RVM

First you need to install RVM by running the following code in Terminal. The Terminal application can be found under /Applications/Utilities/Terminal.app.

[sourcecode language=”objc”]
curl -L get.rvm.io | bash -s stable
[/sourcecode]

Step 2: Install Xcode Command Line tools

There are two ways to install this, firstly you can do it by downloading and installing Xcode, and then installing the Command Line Tools via Preferences -> Downloads -> Click Install next to Command Line Tools. Or you can download the standalone package from developer.apple.com by searching for Command Line Tools in the Downloads Section. However, I think you need to have a developer account for that.

Step 3: Install Ruby

Once the Command Line tools and RVM is installed simple copy paste the following in Terminal:

[sourcecode language=”objc”]
rvm install 1.9.3
[/sourcecode]

Step 4: Check Ruby Version

You can check your installed Ruby version by running the following command in Terminal:

[sourcecode language=”objc”]
ruby -v
[/sourcecode]

A Tutorial on NSTask (Cocoa Development)

I recently started developing for Mac OSX (a recent transition from iOS). My task included me to run some script to do background checks and this is where I needed NSTask. Now the code available is fairly straight forward, a simple copy paste will work – however a bit of explanation is always helpful. Lets start with the full code snippet below:

[sourcecode language=”objc”]
NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: launchPath];
[task setArguments: arguments];
[task setCurrentDirectoryPath:dir];

NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];

NSFileHandle *file;
file = [pipe fileHandleForReading];

[task launch];

NSData *data;
data = [file readDataToEndOfFile];
NSString *response =  [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
[/sourcecode]

The first bit is the NSTask instantiation, pretty obvious. However the next three properties need some explaining. The launch path is the path of the executable you want to run. Most of the executables can be found under /usr/bin, and most of the “system” commands like mv, cat and chmod can be found under /bin. The second parameter is the list of arguments (takes an NSArray). The list is literally the parameters you would type next to the command, eg. mv /usr/bin/ruby /bin/ruby will have the launch path as @”/bin/mv” and arguments as @[@”/usr/bin/ruby”,@”/bin/ruby”]. The third property sets the current working directory, which can be useful for certain applications which require to work in current directories. So if we were to set the current directory path to @”/user/bin” then we could just type in @”ruby” as the first parmeter (in the arguments).

Next block of code is the pipe instantiation. This allows the task to communicate back to the application. We simply instantiate a NSPipe and link it to the task.

We launch the task.

Finally, when the launch returns, the data is read from the file pointer and converted to an NSString.

Final point: Incase you are using sudo, pass the parameter -s for a terminal window asking for the password. However, the right way to do is to implement Authorization Services. That will probably be my next article.

Adding a search box in a Shopify Liquid Template

One of my recent projects included making a .liquid template for a website based on Shopify. The task was very simple, create a basic blog template with a listing of articles and a search box on the sidebar. Shopify documentation is very good, so setting that up was all easy, however, it took me some time to find on how to implement a search box.

I was actually looking for a search widget, which I believe is not available in Shopify. Instead, all you have to do is to setup a form in the HTML with two fields and submit it to /search. The form includes a text field named “q”, which will take the query and a hidden field named “type”. Type can have the value of article, product or page. Since I wanted to search only the blog, I entered article. You can search for multiple types by separating them with a comma e.g. article,product.

More information can be found on their website here [http://wiki.shopify.com/Admin_search#Searching_only_for_certain_types.]

The final code looked like this:

[sourcecode language=”html”]
<form action="_WEBSITE_/search" method="GET">
<input type="text" name="q" value="" placeholder="Query" />
<input type="hidden" name="type" value="article" />
<input type="submit" value="Search" />
</form>
[/sourcecode]

Setting up WebSockets between iOS and a Java application

I recently had a project where I was supposed to implement a WebSocket in an iOS application and make it communicate with a Java application. I looked around for some good libraries and settled on SocketRocket for iOS. SocketRocket comes with a WebSocket example which was fairly easily to follow, together with a WebSocket server in Python. Setting it up was not too much of a hassel, however once I had setup and run the sample, I moved on to looking for a Java based WebSocket server.

Now the first mistake I made was that I assumed Sockets == WebSockets, and spent countless hours implementing different versions of Java Socket implementations. I kept getting stuck or got this bad header error message. After several attempts it finally hit me that what I really wanted was a specific WebSocket library for Java as well.

Enter TooTallNate’s WebSocket library, which was one amongst many different web-socket libraries which actually worked for me. Again the built-in examples came in handy, and within 5 minutes I had a simple socket server running with which I could communicate with all my clients with. This seemingly simple task took a whole day for me to complete – I hope this can now help others do it much quicker.

TooTallNate’s Java WebSockets: https://github.com/TooTallNate/Java-WebSocket

SocketRocket for iOS: https://github.com/square/SocketRocket

Phonegap 2.1.0 Connection Detection in iOS

[I have been told that this is fixed in Cordova 2.2]

I was working on a PhoneGap application being developed and optimized over Android and iOS. Last I used PhoneGap was about an year ago, a lot has changed in the platform since then. Together with jQuery Mobile, I ended up with a neat little app.

When working on the final touches for  the apps, I ran into a problem: when I detected the internet connection in Android using navigator.network.connection.type, it was working fine (Connection.NONE reported as intended), however, it was not the same for iOS. I double checked the permissions in the Cordova.plist, everything looked fine. It turns out, if there is no connection, the type is “unknown” or Connection.UNKNOWN. So now I am checking for Connection.NONE and Connection.UNKNOWN.

[sourcecode language=”javascript”]
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var networkState = navigator.network.connection.type;
console.log(networkState);
if(networkState == Connection.NONE || networkState == Connection.UNKNOWN) {
alert("You need an active internet connection if you want to save and email the reports.");
}
}
[/sourcecode]

Showing an alert message in iOS

Its been a while since my last post, a lot has happened and there are several unfinished entries waiting to be published. However, this particular one is very small. I recently started developing for iOS and was looking for a way to show alert messages and I could not find a simple one line solution to my problem. I have finally figured out a way to do it, its not exactly one line, but is a single string of code, just need to replace the title and message string and you are good to go!

This may not  be the best way to show an alert, but I felt this is the easiest one.

[sourcecode language=”objc”]

[[[[UIAlertView alloc]
initWithTitle:@"Title"
message:@"Message"
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles: nil] autorelease] show];
[/sourcecode]

Making iPhone Compatible Websites

Its been a while since I have done anything good enough to be posted here. However, yesterday I finally released the iPhone version for my personal website (http://imars.info). I acquired this skill after spending some time designing an iPhone version of pimedia.org.uk, the website of UCL’s student publications. Turns out it is very easy to setup your current website into an iPhone compatible one. All you have to do is a different CSS file for iPhone or Android browsers. For this we will use a simple Javascript script, which will check the browser being used by the incoming user and link the correct CSS accordingly. There is one additional line of code which will let you further control the user interface (like wether the user can zoom into the page or not). And using this simple script and some CSS modifications, you can have an iPhone/Android specific version for your website.

The script itself goes as follows:

[sourcecode language=”javascript”]
if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/Android/i)))
{

document.write("<link rel=’stylesheet’ href=’css/mobile.css’ />");

document.write("<meta name=’viewport’ content=’width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no’>");

}
else {

document.write("<link rel=’stylesheet’ href=’css/style.css’ />");

}
[/sourcecode]

It should be noted that the Safari browser and Android’s native browser both support webkit libraries and much of CSS3.

Creating a folder which collects only unread mail – Apple Mail.app

As requested by Imtiaz Dada, I have looked for and found a solution for viewing only the unread messages in your inbox. This is solved by creating a smart folder in your Apple Mail, which will only have your inbox unread messages. To see on how to create this smart mailbox, watch the video below: (only takes 2 minutes)

http://www.youtube.com/watch?v=s4Oqp0nfG4s

[youtube=http://www.youtube.com/watch?v=s4Oqp0nfG4s]

Mailbox overflow – Creating POP buffer account

Whilst talking to a cousin of mine, he told me about an email related problem which I found to be quite common (at least in my family). While travelling, or on holiday, they are unable to download their emails regularly. As their company’s POP email inbox have very limited space, these accounts soon get full and emails to these accounts start bouncing. My cousin wanted a solution for this, possibly an automated service that would download their emails and empty the POP account.

I started looking around and soon concluded that I needed an online email client that would act as a buffer between the company’s POP account and their Outlook/Mail client, preferably an account with a large inbox so the bouncing problem would not be an issue. I didn’t had to go far for Gmail provided me with the best solution. Gmail has an option for setting up other POP accounts in its settings tab which allows us to ‘pull’ the email into the Gmail account, emptying the company’s POP account in the process. Now since Gmail offers about 7.5 GB of space, it becomes an excellent buffer. Now all we have to do is that configure this Gmail account into our email client and download emails like before.

So now your mail will travel through the following flow chart before getting to you.

Email sent to @rastgar account -> Email appears in @rastgar sitemail -> Email is pulled, now appears in Gmail account, deleted from sitemail -> (by either IMAP or POP) downloaded to client, copy of that mail stays on Gmail, also shows in Outlook/Mail

You will no longer configure your email client to download emails from your company’s (@rastgar.com) POP account.

Most of my friends and family are already forwarding their company’s POP email to a Gmail account (for an online backup), so the configuration below first removes this forwarding, then we re-configure the same Gmail account to pull the email.

While configuring our email client (ie Outlook/Mail) we will have two options, first one is the IMAP configuration, this will simply ‘sync’ your emails rather than downloading them. This way when we delete the junk mail, and reply to emails everything will be updated on the Gmail account too. This means that there is now only one copy of your email and that is on Gmail, the one in your email client is NOT a copy, just a view of that email.

The second option is to tick ‘leave a copy of the message on the server’ while configuring Gmail as a POP account. This will download the email so that there are two copies for every email, one on Gmail and one in your email client (ie Outlook or Apple Mail). However this way the Gmail account will not be updated when you delete the junk mail and reply to emails on your email client.

Setting up your email:

Before starting close your email client, (ie Outlook or Apple Mail). Please make sure there is no unread email in it, since after configuration you will not be able to view them (for POP – since Gmail downloads the mail that comes in after POP is activated, unless selected otherwise)

Removing your current forwarding:

• Login into your email account at sitemail.hostway.com
• Click Settings
• Click Mail Forward (left column)
• Remove forwarding email, click Save

Setting up Gmail account:

• Login into the forwarding account
• Click on Settings (top right)
• Click on ‘Account and Imports’ tab
• Here under ‘Check mail using POP3’ click ‘Add POP3 email account’
• On the form that opens, enter your @rastgar.com email, click ‘Next Step’
• Enter your full email address in the username field, and your password
• Rastgar POP server: pop.rastgar.com
• Incase you are configuring more than one account on the same Gmail account, tick the third checkbox, ‘Label incoming messages’
• click Add Account, if asked to setup to send mail Select No.
• You will now return to the settings page, and your email will be downloaded into this Gmail account.
• Test if this is working fine.
• (if you are planning to use the POP settings, go into ‘Forwarding and POP/IMAP’ tab and select ‘Enable POP for mail that arrives from now on’)

Configuring your email client: (IMAP – Apple Mail)

• Click on Mail (top left in Menu bar)
• Click on Preferences
• Click on Accounts tab
• Disable @rastgar account by clicking on it and navigating to Advanced tab and unchecking enable this account
• Use the ‘+’ button to create a new account
• Enter your name and Gmail email address
• Click Create
• Click on the account, change Email address to @rastgar.com
• Your account is now configured

Configuring your email client: (POP – Apple Mail)

• Click on Mail (top left in Menu bar)
• Click on Preferences
• Click on Accounts tab
• Disable @rastgar account by clicking on it and navigating to Advanced tab and unchecking enable this account
• Use the ‘+’ button to create a new account
• Enter your name, @rastgar email address and password
• Click Create
• Select Account type POP
• Add Gmail Inbox to description
• Incoming mail server: pop.gmail.com
• Username: @Gmail user name without @gmail.com, password: Gmail account password
• Click continue (new form will open)
• Enter Rastgar SMTP in description
• Outgoing Mail Server: pop.rastgar.com
• Check on ‘Use only this server’
• Check on ‘Use Authentication’
• Enter your @rastgar account details
• Click Continue
• Click Connect if asked to verify rastgar server
• Click Create
• Under Advanced tab, uncheck ‘Remove copy from server after retrieving a message’
• Close the window
• Click Save
• Your account is now configured

imars.info Updated!

And here comes my yearly site update post, and this year its all about web 2.0. I have redone the whole design, the content, everything from scratch. The result is the very simple and clean template, with big fonts and some cool JS implementations. So here it is, visit the site @ http://imars.info/ and let me know wht u think of it!