Category Archives: Code

Refactoring Tip: Eliminating Model.find(params[:id]) Duplication

In a controller, you’ll commonly have a method that requires you have an instance variable containing the object you’re working with. An example would be the show, edit, update, and destroy methods (REST).

To eliminate having find(params[:id]) in multiple methods, you can use before_filter, like this:

class Admin::PostsController < Admin::ApplicationController
  before_filter :find_post, :only => [:show, :edit, :update, :destroy]
  rescue_from(ActiveRecord::RecordNotFound) { |e| render :text => "

Post not found

" } def index @posts = Post.find(:all) end def show end def new @post = Post.new end def create @post = Post.new end def edit end def update end def destroy end protected def find_post(id = params[:id]) @post = Post.find(id) end end

(Thanks Jon)

Using Javascript to Populate Forms During Development

During development, working with forms quickly gets annoying because you have to constantly fill in each field, sometimes with unique info. One way around this is to write a little Javascript code that just populates the fields. I use something like this on the bottom of the form. I had jQuery no-conflict mode on in this case. In your app you might be able to get away replacing _j() with $():

<% if ENV['RAILS_ENV']=='development' -%>


<% end -%>

Learning to Read and Grok Other People’s Code

One reason many people don’t contribute to open source apps is because they find it daunting to look through somebody else’s code. Some might even think that it’s just simpler to write something from scratch than to study someone’s work. This isn’t true, and reading foreign code is something get used to and excel at over time. It’s a necessary skill for every programmer, and has many benefits.

A huge benefit is the massive amount of information you learn and get accustomed to in a short period of time. There’s no way to download O’reilly PDFs into your brain just yet, but grokking source code written by those much more experienced than you is one of the fastest ways to see and practice everything you’re been learning in theory (books, sites, classes).

It’s certainly overwhelming to jump head first into a huge app trying to understand every line. I think it’s common for people to open up some code, read it for a few minutes and then never touch it again because they don’t understand it. This was the case with me when I began programming. Here are some ways i used to justify putting off the need to read third party code.

Their code style didn’t suit my taste, i.e., they add the opening curly bracket under the function definition, and I would find myself changing their brackets and formatting more than I spent time actually looking at the logic.

I told myself I would learn much more by re-inventing the wheel, or have more control over my app if I built it from scratch. This is only partial true, but the cons outweight the pros. Reinventing the wheel means diviating from writing program logic and having to learn something that might not even remotely be related to the project I intended to start or finish. Here’s an example that used to be common.

Continue reading Learning to Read and Grok Other People’s Code

Script to Quickly Setup WebApp Environment and Domain

Just sharing a script I wrote to quickly deploy WordPress (and eventually a few other webapps) sites, which somebody might find useful. This uses Linode‘s API* to add the domain name to the DNS server along with some subdomains. If you’re using another server, (Slicehost, your own, etc), you can alter the dns class to use that API, or just ignore the DNS stuff completely; Its optional.

This will be updated periodically as I refactor and add support for more apps (notably Joomla and Clipshare – though this would violate their terms unless you have the unlimited license). This was written primarily because I couldn’t stand setting up another vhost and WordPress installation. There are plenty of existing deployers but I plan on adding very specific features and tweaking this for in-house work. I also wanted to try Rio (Ruby-IO). GPL license. Go nuts.

* As of 10/11, the apicore.rb file on the site has some syntactic errors in the domainResourceSave method. I sent an email out to the author about it. Problems aren’t major. You can get my apicore.rb here.

This won’t run unless you create the appropriate folder structure in /etc/mksite/. I’ll get going on this in a bit. See the code below:

Continue reading Script to Quickly Setup WebApp Environment and Domain

Spy on your Enemies and Loved Ones for Fun and Profit

The following is a stealthy keylogger I wrote in C a few years ago called LogThatShit (LTS). It was written on and for Windows XP, and probably works on Vista, but User Account Access (UAC) might prompt the user for a password. It began as a complete Remote Administration Tool (RAT) named Overdose. I realized that the keylogger is the most important part of the RAT and decided to branch that off into a separate project.

As of 09/09/08, LTS remains undetectable by anti-virus software. It bypassed the heuristic analysis engines of its time, but the more advanced ones today might pick it up.

I am releasing the source code under the GPL license, with no warranty whatsoever, for educational purposes only. I don’t use it, and I don’t suggest you use it. Usage might be illegal where you live, if not just unethical. I will not compile/send out any binaries. I don’t even know if it’ll compile out of the box.

Feature set (This was written a long time before the app was complete, and was never updated)

A key stroke logger for Windows 9X/NT/2K/XP

  • Hijacks a process, meaning it will not show up on the task manager.
  • Bypasses heuristics engines.
  • Starts up automatically on boot. Does not show up in msconfig.
  • Logs OS, timestamp, Windows username, and the title and path of the window that currently has focus.
  • Can be updated or removed from the victim’s computer remotely.
  • Ability to download and and launch an executable silently from an FTP site.
  • Does not show up on the task manager on both 9X and NT platforms.
  • CPU and memory usage do not increase. No noticeable performance or memory hit.

Geeky Details:

  • Written in ANSI C89
  • Developed on XP SP1. Tested for Windows 2000 and XP SP2. Code includes some windows 9X stuff, but it was winged and never tested.
  • Uses a system-wide hook (WH_KEYBOARD).
  • Editor used was gvim (win32) with no plugins and mappings, but with some custom commands added to Windows’ right click context menus, and a bunch of batch (.bat) and Makefiles.
  • Compiled using GNU make and other ported utilities.

The following was somewhat of a list of things I never got around to doing:

  • TODO: Need thorough testing on 9X
  • TODO: Restart feature
  • TODO: Change INFINITE to 1000ms
  • TODO: Don’t use general permissions on mappings / mutex.
  • TODO: Load self into memory and poll for presence, rewrite files if not available (persistence mode).

Technical:
The following is written off the top of my head. When executed, the keylogger may display a customized error message to fool the victim into thinking the program is simply broken or outdated. This is to deter suspicion that the program is malicious, which is the reaction most people have when nothing happens as they sit there trying to open an application.

The logger than copies itself to the SYSTEM32 folder (name is set in the ini config file) and adds itself to system startup. It uses several methods to do this, depending on the OS, but the preferred method is to register itself as an ActiveX object. This hides it deep in the registry, under a unique key, and keeps it out of the msconfig -> startup tab. It also keeps it out of most apps that display programs that launch on system startup.. or at least it did at the time. I think HijackThis and its ilk have caught up now.

When configured, the ‘Stub’ (EXE file) is appended with two DLL files; Hook and Injection. At this point, the stub injects a DLL (injection.dll) into explorer.exe (it also looks for the default browser to use as a backup). This is called DLL injection, and is used to bypass firewalls that only allow trusted programs access to the Internet, else the firewall will give a “notepad2.exe wants to access the Internet. Are you sure you want to allow this?” warning.

Nowadays, firewalls will prompt the user that a program has been altered or has loaded new DLLs (especially if they aren’t in the same folder as the application), but nearly every user will just click “ALLOW” without caring – especially when the application in question is Explorer.exe or Firefox.exe.This also means the user will not notice much in the process manager (ctrl+alt+delete).

Stub remains open but idle; Closing it will unload the DLLs. Most of the work now is done inside Hook.dll. Keys are intercepted at a low level, logged, and then sent where they’re supposed to go. This is better than other loggers that just poll for keys, since it is very efficient and will not cause a memory/performance hit.

The logfile will store the title and file path of the application that has focus, and every keyboard key sent to that application. Capslock, backspace, enter, tab, shift, “special keys” and so forth are also logged and labeled. I.e., Shift might be [LSHIFT] or [RSHIFT]. All timestamped.

An example would be:

Biodegradable Geek > Login – WordPress – Firefox (c:programsfirefoxfirefox.exe)
——————————————————————————-
[04:39:93] [RSHIFT]Isam[TAB]password123[ENTER]

There’s a few more features and technical details. View the source below:

// This software file (the "File") is distributed under the terms of the
// GNU General Public License Version 3, (the "License"). You may use,
// redistribute and/or modify this File in accordance with the terms and
// conditions of the License, a copy of which is available along with the
// File in the license.txt file or by writing to
//  Free Software Foundation, Inc.,
//  59 Temple Place,
//  Suite 330, Boston, MA, 02111-1307
//
//  or on the Internet at http://www.gnu.org/licenses/gpl.txt.

// THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND. THE AUTHOR
// DOES NOT TAKE ANY RESPONSIBILITY FOR ANY DAMAGE OR LEGAL ISSUES YOU MAY
// FACE WHEN USING THIS APPLICATION. PLEASE NOTE THAT LTS WAS WRITTEN AND
// RELEASED FOR *EDUCATIONAL* PURPOSES ONLY AND IS NOT INTENDED TO BE USED
// FOR ANYTHING THAT MAY BE AGAINST THE LAW WHERE YOU LIVE. IF YOU DO NOT
// WANT THAT RESPONSIBILITY, PLEASE DONT COMPILE OR USE THIS APPLICATION.

View the source here: http://code.biodegradablegeek.com/LogThatShit/

How To Use Fixtures to Populate Your Database in Rails

UPDATE: I’ve been using this method for awhile now: http://railspikes.com/2008/2/1/loading-seed-data

Seed data is data that the app is dependent on. It is data that has to exist if you were to wipe the database clean and reload your schema. Some examples would be a list of cities/states, a list of categories, or the initial ‘admin’ user account.

Most people looking at this thread want seed data rather than to populate their database with test/generated content. For the latter, you can go the route below or try Forgery

This is a response to the email I’ve been getting asking me how to use fixtures to load data into a database.

You want to create dummy entries in your Rails app, either for testing, for development, or for production, to make your site appear popular. Whatever the reason, populating your database can be done easily using fixtures.

While rake/fixtures/migrations can get a lot more complex, this will be a brief introductory example.

Initial App setup

$ rails characters
$ cd characters/

Edit config/database.yml – We only need a development database. So open up PHPMyAdmin or the MySQL command shell and:

mysql> CREATE database characters_development;
Query OK, 1 row affected (0.00 sec)

(I’m assuming you’re using MySQL. You can use anything; SQLite, Postgres, etc..)

Create a model and a table in the database (using a migration)

$ script/generate model Character
      exists  app/models/
      exists  test/unit/
      exists  test/fixtures/
      create  app/models/character.rb
      ....

$ vim db/migrate/001_create_characters.rb

Sexy migration:

class CreateCharacters < ActiveRecord::Migration
  def self.up
    create_table :characters do |t|
      t.string  :name, :alias, :motto
      t.timestamps
    end
  end

  def self.down
    drop_table :characters
  end
end

Now migrate development (default environment):

$ rake db:migrate

Create the characters fixture

$ vim test/fixtures/characters.yml

Continue reading How To Use Fixtures to Populate Your Database in Rails

Got API? Instantly Search API Documentation

gotAPI.com does an excellent job congregating API documentation for numerous programming languages under an AJAX interface. No more bulging neck veins or fulmination when you can’t remember the order of those pesky arguments.

No support for your favorite language? Contribute.

You can add a gotAPI Search Widget to your site: http://www.gotapi.com/widgets/index.html
See Ruby/Rails widget below (requires Javascript). Still in beta and might have UI issues, but it’s functional. Try typing map or validates and hitting enter.

Quick Ruby / Rails lookup

powered by gotAPI.com

How to POST Form Data Using Ruby

POSTing data on web forms is essential for writing tools and services that interact with resources already available on the web. You can grab information from your Gmail account, add a new thread to a forum from your own app, etc.

The following is a brief example on how this can be done in Ruby using Net::HTTPand this POST form example.

Looking at the source (interlacken.com/webdbdev/ch05/formpost.asp):

<form method="POST" action="formpost.asp">
<p><input type="text" name="box1″ size="20″ value="">
<input type="submit" value="Submit" name="button1″></p>
</form>

We see two attributes are sent to the formpost.asp script when the user hits the submit button: A textbox named box1 and the value of the submit button, named Submit. If this form used a GET method, we would just fetch the URL postfixed with (for example) ?box1=our+text+here. Fortunately, Ruby’s Net::HTTP makes posting data just as easy.

The Ruby code:

#!/usr/bin/ruby

require "uri"
require "net/http"

params = {'box1′ => 'Nothing is less important than which fork you use. Etiquette is the science of living. It embraces everything. It is ethics. It is honor. -Emily Post',
'button1′ => 'Submit'
}
x = Net::HTTP.post_form(URI.parse('http://www.interlacken.com/webdbdev/ch05/formpost.asp'), params)
puts x.body

# Uncomment this if you want output in a file
# File.open('out.htm', 'w') { |f| f.write x.body }

Sending the value of button1 is optional in this case, but sometimes this value is checked in the server side script. One example is when the coder wants to find out if the form has been submitted – as opposed to it being the user’s first visit to the form – without creating a hidden attribute to send along w/ the other form fields. Besides, there’s no harm in sending a few more bytes.

If you’re curious about URI.parse, it simply makes the URI easier to work with by separating and classifying each of its attributes, effectively letting the methods in Net::HTTP do their sole job only, instead of having to analyze and parse the URL. More info on this in the Ruby doc.

Assuming no errors, running this example (ruby postpost or chmod a+x postpost.rb; ./postpost.rb) yields:

<form method="POST" action="formpost.asp">
<p><input type="text" name="box1″ size="20″ value="NOTHING IS LESS
IMPORTANT THAN WHICH FORK YOU USE. ETIQUETTE IS THE
SCIENCE OF LIVING. IT EMBRACES EVERYTHING. IT IS ETHICS.
IT IS HONOR. -EMILY POST">
<input type="submit" value="Submit" name="button1″></p>
</form>

In practice, you might want to use a more specialized library to handle what you’re doing. Be sure to check out Mechanize and Rest-client.

Music to Code By – What Do You Listen to While Programming?

Yellow Vinyl Record Spinning

 
Some swear by it, for others it’s a bane: Music while coding /programming. Throughout grade school, we’ve been cautioned not to keep the TV and music on when doing homework, but is it really counter-productive? According to this study (link no longer works), not so, at least for people who are under-stimulated  which probably accounts for most us these days.

Let’s face it: We’re ridiculously overstimulated. How many of us don’t constantly have at least five Firefox instances open, each nesting a dozen or two tabs, F5ing Slashdot and Digg, keeping track of new emails and countless IRC channels, and crawling from one Wikipedia page to another endlessly?
Continue reading Music to Code By – What Do You Listen to While Programming?