Categories
Blog Coding Rails

Using local gems in your Rails application

The Bundler documentation is pretty brief when it comes to creating and using local gems.

In a nutshell, if you want to reference a local gem in your application you have to make sure a .bundle/config file is created in your application directory (local config) or your home directory (global config). Running the command below will create the .bundle/config file in your application’s directory, provided the current working directory your run the command from is your application’s directory:

bundle config local.GEM_NAME /path/to/local/git/repository

One problem you might run into is that this file gets disregarded when you run “bundle install”.
The solution is fairly simple:
You must specify the gem’s source and branch explicitly in your Gemfile, such that, if you were to include the udemy gem you would setup your Gemfile as follows:

gem 'udemy', git: 'git@github.com:jonaphin/udemy.git', branch: "master"

Running bundle install should yield the following message:
Using udemy (0.1.4) from git@github.com:jonaphin/udemy.git (at /local/path/to/udemy)

I hope this helps you as I wish it had helped me 🙂

Categories
Coding Geekery Linux

Generate a Self-Signed SSL Certificate in 2 Easy Steps

Ever wanted to generate your own domain’s SSL certificate?
Let me first put it out there: It’s a bad idea if you intend to make your domain publicly available.
Ahh, the air’s more breathable now that the elephant’s out of the room!

You’re still here? Good. Let’s proceed!

Let’s say you do need a self-signed SSL certificate for one of your domains, and you don’t feel like typing more than two commands. You’re in luck!
First and foremost, find a cosy (and preferably organized) place for your certificates to live. I personally like to stick them in /data/ssl/certs/[domain]/[subdomain]/, but to each their own.

Command #1:
openssl req -new -nodes -keyout domain.key -out domain.csr
This command generates both a domain server key and a certficate signing request, which you’ll need to generate your crt file in command #2.
It will ask you a bunch of questions. The important one is the “Common Name”, as it is the one that needs to match your domain.
For example, I setup a certificate for https://www.quotir.com, so I set the common name to “www.quotir.com” hmmkay?

Command #2:
openssl x509 -req -days 365 -in domain.csr -signkey domain.key -out domain.crt
There you have it, your domain certificate will be valid for a year!

As a bonus, here’s how I setup nginx to redirect all https traffic to http, using my shiny new self-signed SSL cert:

In nginx.conf

server {
listen *:443;
ssl on;
server_name quotir.com;
rewrite ^(.*) http://www.quotir.com$1 permanent;

ssl_certificate /data/ssl/certs/quotir/www/quotir.crt;
ssl_certificate_key /data/ssl/certs/quotir/www/quotir.key;
}

Happy Sysadmining friends and don’t be shy, say hello!

Categories
Linux

Ubuntu 13.04 Final Beta is out!

I had the chance to upgrade from Ubuntu 12.10 to 13.04 Final Beta last night on my netbook. As is customary now, every six months this public transit-friendly computer goes through a mandated OS upgrade… and what a treat!

The Unity Desktop & Netbook environment is maturing and it shows! It’s much faster, more responsive, and allows me to fully enjoy my morning treat: Programming some Rails while riding Caltrain (Is there a pun? Didn’t think so either).

So, how does one upgrade to a pre-release version of Ubuntu? Easy!

Open the Terminal and type the following command:
sudo do-release-upgrade -d

There is a GUI-based way to do it as well, but who would want to do that anyway!?

Categories
Blog Startup News

Why The Launch of ShareBetaKeys.com Is a Success

ShareBetaKeys.com is a success.

You may think it arrogant of me to say, I know. Nevertheless, I will not mince my words, our launch was a real success.
You see, the first thing we should discuss a little is what success really means for us.
Success, to be measured appropriately, must be quantified. Society shapes in us a generic, contextual understanding of success.
Having a successful career usually means being able to excel at what we do and grow all the way to the top within that path.
A successful person is usually thought of as having made enough money to go retire sipping Pina Colada under a palm tree on some exotic, remote island.
In the case of ShareBetaKeys, success had its own meaning, and no, traffic or money were not factored into our definition.

So what made us so audaciously claim it a success?

Release: Your First Measure of Success

The first and simplest reason is SBK (ShareBetaKeys.com) is released and ready to serve. Given that many startups/products fail before launch, we can proud ourselves with having met the most important initial milestone: Releasing.

Identify a Pain Point

ShareBetaKeys was born out of a real need. The idea came up when browsing Reddit. Someone had pasted 200 keys for Icarus Online in a post, and at the time of reading many top comments were just complaints about how Steam had locked people’s accounts. Some readers had tried 2, some 20, some 3 before either getting lucky (and locked out), or unlucky (and still locked out).
My heart-beat raced, giving all its power to pumping the Startup “Eureka” moment up my veins and into my head. I had identified a “pain point”.

Pasting your keys on a forum thread has to be the worst way of dealing with distribution in post-web1.0 era. Sure, it crowdsources the certainty of key redemption (assuming there are way more users than there are keys), but any customer-oriented dev shop would not want to waste its gamers’ time or lock them out of game platforms such as Steam. Solving this pain became the raison-de-vivre of SBK. Identifying a pain point is one great way to start a new product. It instantly gives meaning to the product’s existence.

Solve the Problem

The first release of our service solves the problem for users in a gracious fashion. Each user may only redeem one key of a given game per account. Two weeks after initial thought, we have a first solution out and ready to help. That, to us, is a success.

A pain-point-driven product’s success should always (though not exclusively) be measured by how well it solves the problem it was born to address.

What’s Next for Share Beta Keys?

Our first iteration is far from the last. We are actively working on a feedback system that would allow developers to stay in touch with “testers/gamers”, as well as a public API for game developers to build plugins that can deal directly with our service, in-game.

The future is bright for SBK, and we hope it might help you deliver or enjoy a top notch experience with game keys distribution.

Categories
Blog Coding Rails

Import CSV Files 100x Faster in Rails 3

I recently tasked myself with helping a good friend import a relatively large (1 million+ records) CSV file into a database powering a Rails application.
The database and code were hosted on a 512MB Chunk at Chunkhost, which is also where I host once hosted Quotir (I now use DigitalOcean, they really rock!).
As any well-intentioned Railsist would, I embarked on the journey armed with my usual import toolbox, which consists of:

  • A Rake Task to handle the import
  • FasterCSV (which is the default CSV import tool in Rails 3)
  • ActiveRecord, because life is so much more beautiful when we don’t have to deal with the database directly

The initial code (pre-optimization) looked a bit like this:

namespace :foo do
  desc "Import bar data"
  task bar: :environment do
    require 'csv'

    headers = [
      "xxx",
      "yyy",
      "zzz"      
    ]

    CSV.foreach("#{path}/bar_data.csv", {headers: :first_row}) do |row|
      bar = Bar.new

      headers.each_with_index do |key, idx|
        bar.send("#{key}=", row[idx])
      end

      # ... do some cool stuff, update some records in other tables

      bar.save

      # ... do some more cool stuff, which happens to also create some new records in other tables
    end
  end
end

In my specific case, the CSV.foreach loop would iterate about once per second. Dear, was I not ready to accept waiting 12 days for this script to finish running!

You see, the beautiful thing about constraints is how they remind you of what is absolutely necessary, and what is well, extraneous.
One doesn’t have to look very far to realize that ActiveRecord is a commodity, a luxury one has to part with when the carriage becomes too heavy for the horse.

So we parted… Me and ActiveRecord bid each other safe travels, and promised we’d meet again.
Now friend, the reason you’re still reading this is because you too, at some point, might have to leave AR (That’s its nickname) by the curb to get to your destination faster.

How did I do it?
Without further ado, here’s what the code above looks like after optimization:

namespace :foo do
  desc "Import bar data"
  task bar: :environment do
    require 'csv'

    headers = [
      "xxx",
      "yyy",
      "zzz"      
    ]

    ActiveRecord::Base.establish_connection

    CSV.foreach("#{path}/bar_data.csv", {headers: :first_row}) do |row|
      sql_keys = []
      sql_vals = []

      created_at = Time.now.strftime("%Y-%m-%d %H:%M:%S")

      headers.each_with_index do |key, idx|
        val = row[idx]

        sql_keys << key
        sql_vals << ActiveRecord::Base.connection.quote(val)
      end

      sql = "
        INSERT INTO bars (#{sql_keys.join(', ')}, created_at, updated_at) 
        VALUES (#{sql_vals.join(', ')}, '#{created_at}', '#{created_at}')
      "

      res = ActiveRecord::Base.connection.execute(sql)
      bar_id = ActiveRecord::Base.connection.last_inserted_id(res)

      # do some cool stuff, like create records in other tables that reference bar_id
      # use ActiveRecord::Base.connection.execute(your_sql) in subsequent calls.
      # no need to close the connection, or reopen it before calling execute.      
    end
  end
end

 

It all starts with a call to
ActiveRecord::Base.establish_connection
The line above will establish a direct connection with the database set by your environment in the config/database.yml file.

Two important details to note in the code above:
ActiveRecord::Base.connection.quote(val)
This is one of the proper ways to escape your SQL. Use it. If you favor prepared statements, then by all means look at sanitize_sql_array
The second detail is the time stamps. If you’re working in Rails you will want to add the time stamps for created_at/updated_at manually, as they cannot be null.

And this is how my import script went from taking 12 days to run to taking 3 hours only!

See that? A tavern! This is where me and this post will rest for a while, right by the “Post Comment” button, so how about you stop by and share your thoughts on our journey and yours, fellow traveler?

Note: This code should work with Rails 2 with minimal changes.

EDIT: As mentioned by “Taladar” on the Reddit thread for this post, using LOAD DATA INFILE can drastically reduce import times. Depending on the case at hand (and specifically if it’s a simple record insert per CSV row), this might be the optimal solution.

Categories
Blog OS X

Speed up the Terminal Launch on OS X Lion

Does the following trick work on Snow Leopard? I think it does. But if I were to “think”, I’d think you should be on Lion, though this is not the purpose of this post.

Sooo, back to our trick. Ever launched the terminal and noticed that it may take a good 2 to 5 seconds to open? Even on your stellar 16-core Mac Pro? Fear no more. There’s a trick that will bring that benchmark down to well, hmm… a split second!

Open the Terminal (Cmd + Space, then type “Terminal”, then press “Enter”). Are we there yet? Good.

Now paste in the following excerpt and press “Enter (or Return)”:
touch ~/.hushlogin

Quit the Terminal (Cmd + Q) and relaunch. Be proud.

Credits: User “thought_alarm” on Hacker News – Source

* EDIT *
Sorahn, an awesome user from the Reddit community contributed this little gem to us:
Dumping the *.asl logs seems to speed up login even more. If like me, you’re after every millisecond you can get and don’t mind spending an extra 5 seconds to make it happen, then here’s the command you need to run:
sudo rm -rf /private/var/log/asl/*.asl

Full Credits here.

 

Categories
Blog Linux

How Ubuntu Beat Apple at Its Own Game

Cmd + Space to Open

Remember Spotlight?

Well, it seems like Mark Shuttleworth and his team at Canonical took a shot at it and hit the Apple straight in the seeds!

For those of us less familiar with OS X, Spotlight enables you to quickly access files or applications. Just start typing a keyword and your app or file’s name will show up as an option that you can select to access, much like Google’s Instant Search or the Windows Start Menu Search.

… And then there is HUD.

In Ubuntu 12.04 (Precise Pangolin), HUD takes the Spotlight premise and extends it to your current context.

You’re in a browser? Type a URL in HUD and there goes your browser making good on fetching your website! Search help, history, option menus. It’s ALL in HUD!

In an Image Editor? Same principle. Apply filters, resize, add layers, change colors all from the HUD. HUD is like the best friend you’ve never had, always listening and ready to help, no matter what the context!

As the great Ed DJ once said:
Powered by Wordpress Plugins - Get the full version!

Now, Ubuntu users can swear by the HUD! More about it in this video:

 

 

Categories
Blog Coding

Speed up local HTTP requests on OS X Lion

Are you developing web applications on OS X Lion? Are you testing on a local server? Is it horribly slow?

You’re still here! Great, that means you, me, and a plethora of other devs have endured the same issue on OS X Lion, specifically.

While it may not be the only source of the slowdowns in your local stack the following trick might prove invaluable to you, as it was to us:

Open your /etc/hosts file, locate the 127.0.0.1 lines, and merge them into one line!

Go from:

To this:

Good Hack is Good

We all owe a big thanks to our friend Joey for the sweet hack! 🙂

Categories
Blog Geekery

Star Wars Episode IV On the Terminal

Star Wars geeks rejoice! It might seem like old news to some, yet finding it brightened my day a tad more.

If you are mildly proficient with a terminal (even the Windows Command Prompt!), chance is you can watch Star Wars Episode IV: A New Hope all made of ASCII art!

It’s a tremendous job by Simon Jansen ( http://www.asciimation.co.nz ) ported to Telnet (with some Terminal tricks) by Mike Edwards (pf-asciimation@mirkwood.net ) and Sten Spans ( http://blinkenlights.nl ).

To enjoy the movie, just open a new terminal window and type:
telnet towel.blinkenlights.nl

More pics below:

Categories
Coding Plugins

Introducing PepperSpray, a jQuery Plugin

PepperSpray

Ever wanted to annoy the hell out of your users?

Look no further. Pepper Spray will drive 99% of your traffic away, thanks to its amazing features:

Disable Right-Click

That’s right! Right Mouse Clicks can be so dangerous we made it simple
to disable it with a single call to:
$.pepperspray("disableRightClick", true);

Disable Text Highlighting (and yes, Images too!)

Don’t allow other suckers to steal your content. You’ve worked so hard copying it from somewhere else!
Here, one shot of pepper spray and look at them poor villagers, with their menacing pitchforks, all up-in-arms! But who cares? No subject shall walk off with her majesty’s property!
$.pepperspray("disableHighlighting", true);

Disable the Back Button Functionality

The world is a prison. Let your users feel it. Oh, one squirt of this pepperspray wonder suffices to piss them off! Ain’t nobody goin’ nowhere!
$.pepperspray("disableBackButton", true);

To download, contribute, or read the documentation, click on the link below:
https://github.com/jonaphin/pepperspray