How to Use the Ls Command on Linux or Mac OS X to Sort Files based on Second in the Timestamp
Here is the one liner.
ls -lhtTr
It will output something like
total 24152
-rw-rw-r-- 1 sean staff 1.0M May 4 14:31:42 2019 4c2caf52cb084ea39a6a65a0e68ee382
-rw-rw-r-- 1 sean staff 1.0M May 4 14:31:44 2019 76eeeea5d...
Written by Sean Behan on 05/04/2019
How to Use the Ls Command on Linux or Mac OS X to Sort Files based on Second in the Timestamp
Here is the one liner.
ls -lhtTr
It will output something like
total 24152
-rw-rw-r-- 1 sean staff 1.0M May 4 14:31:42 2019 4c2caf52cb084ea39a6a65a0e68ee382
-rw-rw-r-- 1 sean staff 1.0M May 4 14:31:44 2019 76eeeea5d...
Written by Sean Behan on 05/04/2019
Super Simple Router for React Without Any Dependencies
Here is some very simple code to render React components dynamically without using a framework or routing library.
It doesn't cover pushState and URL parsing, so in that sense it isn't a routing library. But it does let you render components from othe...
Written by Sean Behan on 11/16/2018
How to Reset and Clear a Form Field or Textarea with Stateless Components in React
Stateless components are nice. They are simple to use and understand but can become tricky when you start thinking about data and how to manage state. In general, the consensus seems to be that if your UI is going to need state, then at least the componen...
Written by Sean Behan on 10/21/2018
How to Read and Write to a Single Cell Using PHP and Google Spreadsheets API
This post assumes you've created a project with Google's web console and downloaded a client_secret.json file from the credentials page. If not, more info is here..
https://www.twilio.com/blog/2017/03/google-spreadsheets-and-php.html
Note: The tuto...
Written by Sean Behan on 10/11/2018
How to Flatten and Merge Arrays in PHP
There is no built in function for taking a multi dimensional array in PHP and flattening it into a single array. However, it's pretty easy to accomplish in a one liner. Here is the code
...
Written by Sean Behan on 09/28/2018
Parsing URL Parameters with Swift
Here is an extension you can use in your Swift (v4) projects that makes it easy to parse parameters from a url.
Given a url like, "http://example.com/?x=1&y=2", you can extract the x and y parameters into a key, value data structure.
Here is the s...
Written by Sean Behan on 09/23/2018
How to Handle Uploading Really Large Files in PHP
PHP has some default limits that do not work out of the box when you want to work with uploading very large files.
So there are a few configuration changes you have to make to the defaults that come with PHP. These are defined in you php.ini file.
The...
Written by Sean Behan on 09/20/2018
How to Chunk Large Files in Swift
How to Chunk Large Files in Swift (4.1)
It takes a bit of work but this is the solution I found that finally worked, thanks to this Stack Overflow thread https://stackoverflow.com/questions/46464177/split-data-in-chunks-and-upload-to-server
The example ...
Written by Sean Behan on 09/15/2018
How to Extract all Images from a Webpage with Ruby
Here is a little ruby snippet that will download all pictures from a webpage.
Rather than using XPath, we are going to first reduce the source code to capture everything inside of quotes. Some websites use JSON w/in a script tag to lazy load images an...
Written by Sean Behan on 08/01/2018
How to Get GPS Location Information from Address String with Swift and iOS CLGeocoder
You can use CLGeocoder geocodeAddressString method. It will return an array of CLPlacemark objects that contain gps coords and city, location info.
let address = "Burlington, Vermont"
CLGeocoder().geocodeAddressString(address, completionHandler...
Written by Sean Behan on 06/11/2018
How to Get GPS Location Information from a Photo or Movie with Swift and UIImagePickerController
This code assumes you're using the UIImagePickerController. If not you will need to get an image url another way.
But, If you are using UIImagePickerControllerDelegate then it will supply the asset's url in the `info` dictionary . From the asset's url...
Written by Sean Behan on 06/11/2018
How to Dynamically Call a Method from a String in Swift
You have to subclass NSObject
class Car : NSObject {
func drive(){
print("Driving..")
}
}
let car : Car = Car()
car.perform(NSSelectorFromString("drive"))
Written by Sean Behan on 06/09/2018
How to Check if Your iOS or MacOS App is Connected to the Internet
Is your app connected to the internet? You can use this standalone class to check! There are no dependencies so you can copy/paste it into your project without needing to install another framework.
With this class it's as simple as running `Reachabili...
Written by Sean Behan on 06/08/2018
How to Flush or Erase Cache of Your XCode iOS or MacOS Cocoa App
If you're working with an XCode application, either iOS or MacOS, and want to do a completely clean build and delete the cache, it's simple.
Execute this command from the command line..
defaults delete your.apps.bundle.id
Where "your.apps.bundl...
Written by Sean Behan on 06/08/2018
How to Find the Directory Locations Your XCode App Uses
You can add this snippet to your application, say for instance in your `viewDidLoad` function, that will print to the XCode console, the location of your app while it's being developed.
// prints the location of asset my-added-file.txt that you've ad...
Written by Sean Behan on 06/06/2018
How to Find Postgres Log File and Postgres Data Directory from PSQL
If you want to find the location of your log file in Postgres, you'll need to hop into a Psql session..
psql dbname
Then it's as simple as running..
show data_directory ;
Which will output the data directory, in my case..
/Users/sea...
Written by Sean Behan on 05/25/2018
How to Use Python Shutil Make_Archive to Zip Up a Directory Recursively including The Root Folder
The documentation for Python's shutil.make_archive is very confusing. Considering that the arguments to this function only need to be source and destination, makes it even more frustrating to try and reason about.
Here are the relevant docs from the p...
Written by Sean Behan on 05/16/2018
How to Just Get SQL Statement Error with SQLAlchemy Python Database Wrapper
If you're working with SQLAlchemy, the best database driver for Python, and want to see only SQL syntax errors, you need to use the StatementError exception class. On it, is an attribute `orig`, that contains just the SQL syntax error... and not any data...
Written by Sean Behan on 05/10/2018
Extension for Encoding and Decoding Strings in Base64 in Swift
Here is an extension to base 64 encode and decode strings in Swift (3)
extension String {
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self) else {
return nil
}
return String(data: data, encoding: ....
Written by Sean Behan on 05/02/2018
How to Emulate Double Tap for Progressive Web Apps (PWA) iOS and Android
The double tap event isn't supported in libraries like jQuery Mobile (out of date anyway). But coding up your own function is very easy.
We will compare time in milliseconds between tap or click, events. The reason for both tap and click events is due ...
Written by Sean Behan on 04/08/2018
How to Log and Query SQL Queries Hitting Your Database with MySQL
Here is some code just in case you want to look at and query the queries hitting your MySQL database.
Enter this from the mysql client console.
mysql> SET GLOBAL log_output = 'TABLE'
mysql> SET GLOBAL general_log = 'ON';
mysql> select event_ti...
Written by Sean Behan on 03/17/2018
How to Time Piped *nix Commands
If you want to time how long a piped bash command take, use the `time` command followed by your commands in parens like so..
time (ls -lha | wc -l)
Written by Sean Behan on 12/11/2017
How to Parse Query Strings in PHP
Here is a quick snippet for parsing query strings in PHP. You can use the `parse_url` and `parse_str` methods. `parse_str` will create a variable for you populated with results.
$url = "http://www.seanbehan.com/path/?param=key";
parse_str(parse_url...
Written by Sean Behan on 12/04/2017
How to import CSV into SQLite3
To import a CSV file into SQLite is easy.
sqlite3 my.db
.mode csv
.import path/to/file.csv name_of_table
And done.
Written by Sean Behan on 12/03/2017
How to Cast an Array to an Object with PHP
It's short and sweet.
$obj_from_array = (object)['key'=>'val'];
echo $obj_from_array->key;
Written by Sean Behan on 12/02/2017
How to Tag and Push a Release with Git
Set the `-a` and the `-m` flags like so
git tag -a v1.0.0 -m "Note about the release goes here"
Then to push the tag to a repository
git push origin --tags
And that's it!
Here are the docs [https://git-scm.com/book/en/v2/Git-Basics-Tag...
Written by Sean Behan on 11/29/2017
Simple Way to Calculate the Odds of Something Happening
Here is a quick way to express a chance of something happening.
This is an example in JavaScript that gives you a 1 in 3 chance of being true.
[true, false, false].sort(function(){ return Math.random() >= 0.5 ? 1 : -1 })[0]
Basically, we popu...
Written by Sean Behan on 11/27/2017
PHP Headers for Sending CSV File Downloads
If you would like to force a file download prompt to the user, instead of just outputting the text to the browser, use the following headers.
...
Written by Sean Behan on 11/25/2017
XPath with HTML in PHP One Liner
Here is a one liner for using XPATH with HTML in PHP
$doc = new DOMXPath(@DOMDocument::loadHTML(file_get_contents("https://www.reddit.com/r/PHP/")));
Now you can use XPATH to query the html..
foreach($doc->query("//a") as $el){
echo $el->no...
Written by Sean Behan on 11/14/2017
How to Calculate Age with PHP
Calculate age in PHP
$your_birthday = '1982-08-29';
$difference = date_diff(date_create(), date_create($your_birthday));
$age = $difference->format('%Y');
// 35
Short and sweet
Written by Sean Behan on 11/11/2017
How to Use Named Variables with Postgres and PHP PDO Driver
You can write reusable scripts with Postgres by taking advantage of named variables.
A named variable starts with a `:` in your sql script. Here is an example
select :a_number
You can then use this statement with `psql` and the `--variable` fl...
Written by Sean Behan on 11/11/2017
How to Get a Random Item from an Array in PHP
Use this snippet for grabbing a random item from an array in php
$fruits = ['apple', 'banana', 'carrot', 'date', 'elderberry'];
echo array_rand(array_flip($fruits));
// => 'banana'
PHP's `array_flip` makes the keys the values and the valu...
Written by Sean Behan on 11/10/2017
Connect to Postgres on Heroku using DATABASE_URL Config Var with PHP and PDO
Unfortunately PHP's PDO constructor doesn't take a database connection url (in a format that Heroku makes available as a config var) as an argument. It has its own, rather odd syntax.
However, it's easy enough to extract url parts with the `parse_url`...
Written by Sean Behan on 11/10/2017
How to Slugify a String in PHP
Here is a snippet for generating a URL friendly slug in PHP
function slugify($string){
return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $string), '-'));
}
And you can use it in your code like so
...
Written by Sean Behan on 10/26/2017
How to Generate a UUID in PHP 7
Here is a little snippet for generating a UUID in PHP 7
function uuid(){
$data = random_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_...
Written by Sean Behan on 10/26/2017
Apache Rewrite Rule for Mapping to index.php in Sub Folders
Below is an example URL structure with rewrite rules using an Apache .htaccess file.
GET /a/ => a/index.php
GET /a/b/ => a/b/index.php
GET /a/b/c/ => a/b/index.php
This URL mapping will give you pretty URLs in PHP without needing t...
Written by Sean Behan on 10/20/2017
Manual ManyToMany Through with Django's ORM
Here is a code snippet that demonstrates how to set up a __ManyToMany through__ relationship in Django. In Rails, the equivalent would be called a __has_many through__ association.
If you set the __through__ argument on the ManyToManyField, Django wil...
Written by Sean Behan on 07/21/2017
How to Read Response Body HTML with Javascript Fetch Method with React Native
In React Native you see a lot of tutorials and articles using the `fetch` method when interacting with `JSON` APIs. It's great for this and the the pattern looks like this
fetch(url).then((resp)=>{ return resp.json() }).then((json)=>{ console.log(json...
Written by Sean Behan on 07/17/2017
How to Fix Raw query must include the primary key with Django ORM
When running raw SQL queries in Django you must include a primary key otherwise an invalid query exception is raised. Normally this is fine but when running more complex queries a primary key may not be available or even make sense.
There is a simple ...
Written by Sean Behan on 07/15/2017
Simple SQL for Counting New Signups
Here is a little snippet that will return new signups (or new records) for today
select id, email, created_at::date date from signups
where email not in (select distinct email from signups where created_at < current_date)
Written by Sean Behan on 07/13/2017
How to Find An SQLite Database with React Native and the iPhone Simulator.
I spent a few hours digging around my file system using `find` and `grep` hunting for my SQLite database that the iPhone Simulator was using for my React Native project. And no luck.
But I found a simple solution was to use `react-native log-ios` and ...
Written by Sean Behan on 06/29/2017
Active Admin Rails 5 undefined method per_page_kaminari
If you run into this error in development, using Rails 5 and Active Admin
NoMethodError - undefined method `per_page_kaminari'
Try the following.
First, make sure you have an initializer in your application.
# in config/initializers/kamina...
Written by Sean Behan on 04/27/2017
Regex for Extracting URLs in Plain Text
Here is a Regex for extracting URLs from text. However, these links will not already be hyperlinked or source attribtues from images or iframes.
This example is in PHP. I was trying to format a Wordpress page to auto hyperlink but preserve embeded ima...
Written by Sean Behan on 04/14/2017
I Just Published My First PHP Package HTMLXPATH
I just wrote and published my first PHP package on Packagist.com. It's available on [packagist.org](https://packagist.org/packages/htmlxpath/htmlxpath) and the source code is on [github](https://github.com/seanbehan/htmlxpath).
To install the package u...
Written by Sean Behan on 03/28/2017
Matching email addresses in Javascript
Matching email addresses in Javascript
regex = /\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b/img
"hello sean@example.com how are you? do you know bob@example.com?".match(regex)
// => ["sean@example.com", "bob@example.com"]
Written by Sean Behan on 03/24/2017
How to Make Cross Database Queries with Postgres and DBLink Extension
Here are a few snippets for cross database queries. It's important to note that you must be explicit in enumerating the columns and types you are querying. Otherwise, things will probably not work as expected.
-- enable extension
create extension db...
Written by Sean Behan on 03/18/2017
How to send email with Python, smtplib and Postmark
Here is a quick code snippet showing how to send email via SMTP with Postmark without any dependencies. It assumes you are using Heroku and have added the addon. But if not just make sure your api keys are set as environment vars.
from os import envir...
Written by Sean Behan on 03/12/2017
Using Selenium to Drive Firefox Browser for Web Automation
There are a lot of practical uses for automating user behavior in a browser. Everything from testing your web application to logging into Twitter and auto following people.
But first you have to install the tools. Here is everything you need to run yo...
Written by Sean Behan on 03/09/2017
How to Import/Export a Database from One Heroku App to Another Heroku App
Heroku is awesome! Let's say we want to copy a production database to a staging database.
We can use the `pg:backups:restore` command to accomplish this. Here is an example. For the source database we are using the `production-app-name` and for stagi...
Written by Sean Behan on 03/07/2017
Reshape an Array of Form Inputs for Flask with getlist()
This is how to reshape an array using Python without Numpy.
This is a fairly simple task but it can be a little confusing to wrap your head around. I ran into this problem while working with Flask, working with array from form fields.
I wanted to us...
Written by Sean Behan on 03/07/2017
Trigrams, Bigrams and Ngrams in Python for Text Analysis
Creating trigrams in Python is very simple
trigrams = lambda a: zip(a, a[1:], a[2:])
trigrams(('a', 'b', 'c', 'd', 'e', 'f'))
# => [('a', 'b', 'c'), ('b', 'c', 'd'), ('c', 'd', 'e'), ('d', 'e', 'f')]
You can generalize this a little bit more
...
Written by Sean Behan on 03/06/2017
How To Create a Dump File in Postgres Compatible with Heroku
When Heroku creates a dump file of your Postgres database it uses the `-Fc` option
It is equivalent to running
pg_dump -Fc -d name_of_db > name_of_db.dump
This command will let you import your database with the `pg_restore` command
pg_rest...
Written by Sean Behan on 03/06/2017
How to Fix xcrun: error: unable to find utility "instruments", not a developer tool or in PATH
I just got a new machine and downloaded XCode. I used git to clone my ReactNative project from Github. I have everything ready to go. But when I run `react-native run-ios` I see
xcrun: error: unable to find utility "instruments", not a developer tool ...
Written by Sean Behan on 03/05/2017
How to Decorate Imported Libs in Python for Jinja Template Filters in Flask
To decorate an imported function in Python you would do something like this
# in ./lib.py
def function_name():
# function body
And then in your program you could decorate it like this
from lib import function_name
function_name = decorat...
Written by Sean Behan on 03/04/2017
Get Method Name as String in Python
Here is how to get the string representation of a method in Python
def my_method_name():
print "Hello World"
my_method_name.__name__
# => 'my_method_name'
Short and sweet!
Written by Sean Behan on 03/04/2017
Destructuring Dictionaries in Python
Here is a quick and dirty way to destructure dictionaries in [Python]
d = {'a':'Apple', 'b':'Banana','c':'Carrot'}
a,b,c = [d[k] for k in ('a', 'b','c')]
a == 'Apple'
b == 'Banana'
c == 'Carrot'
Written by Sean Behan on 03/04/2017
How to Enable UUIDs in Postgres
The first thing you'll need to do is enable the extension
create extension "uuid-ossp";
To test that it's working
select uuid_generate_v1();
For more info on which version of the algorithm you should use refer to the documentation.
...
Written by Sean Behan on 03/03/2017
How to Fix Pypi Upload failed (403): Invalid or non-existent authentication information.
If you run into authentication failure when trying to upload packages
Submitting dist/ to https://upload.pypi.org/legacy/
Upload failed (403): Invalid or non-existent authentication information.
error: Upload failed (403): Invalid or non-existent...
Written by Sean Behan on 03/02/2017
How to Resolve ERROR 1396 (HY000): Operation CREATE USER failed for Error in MySQL
If you run into this error when trying to create a user in mysql, chances are you already have this user account created.
create user 'someuser'@'localhost' identified by 'somepassword';
ERROR 1396 (HY000): Operation CREATE USER failed for 'someuser...
Written by Sean Behan on 03/02/2017
How to Create a Slug in Python with the Re Module
There are a few 3rd party modules that do this sort of thing. But there is a pretty solution using out of the box Python functionality. You don't have to install any dependencies if you use the `re` module.
import re
text = ' asdfladf ljklasfj 2324...
Written by Sean Behan on 03/02/2017
My First Python Package on PyPi - Command Line Blog
I wrote my first Python package over the weekend. It is a simple package that adds a basic blog API to an existing Flask application.
It's called `command_line_blog` and is available [on Github](https://github.com/seanbehan/command_line_blog) and [on ...
Written by Sean Behan on 03/02/2017
Turn Off SSL Verification In Ruby
The following code will disable SSL verification when using Open SSL.
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
It is probably not a good idea to do this in production. But if you are just testing on your development
machine it might...
Written by Sean Behan on 03/02/2017
How To Get A Dict from Flask Request Form
The `request.form` object is an immutable dictionary. An `ImmutableMultiDict` object to be exact. Immutable means that you cannot change its values. It's frozen.
However, you might want to change the values. Say for instance, creating a slug from a ti...
Written by Sean Behan on 03/02/2017
Generate a Gravatar URL with Ruby
To get a Gravatar you need to hash an email address with the MD5 algorithm.
MD5 is a part of the Ruby standard library. Rails loads it by default, but otherwise you will have to require it yourself.
This is a simple implementation.
Gravatar su...
Written by Sean Behan on 04/11/2014
Extract Domain Names From Links in Text with Postgres and a Single SQL Query
This query and pattern will return urls in text all within a single SQL query.
select substring(column_name from '.*://([^/]*)') as domain_name from table_name;
And here it is in a larger query, say for retrieving page view counts for referrers.
...
Written by Sean Behan on 11/23/2013
Python String Format Precision of Float
You can use string interpolation in combination with a dictionary for simple formatting.
print "My name is %(name)s and I have $%(change)0.2f in change in my pocket!" % { 'name': 'Sean', 'change': 00.23 }
# My name is Sean and I have $0.23 in chang...
Written by Sean Behan on 11/20/2013
How To Install Pyscopg2 Python Postgres Driver on Mac OSX with Homebrew, Postgres.app and VirtualEnv
You might have to append the path of the Postgres.app bin directory to your path in order to install the Python driver for Posgres.
export PATH=$PATH:/Applications/Postgres.app/Contents/MacOS/bin
To find the location of the application try this
...
Written by Sean Behan on 11/19/2013
A Ruby Regex for Removing Links and Images from Text
r = /https?:\/\/[\S]+/i
you_string.gsub(r, '')
Here's the rubular regex to play around with yourself http://rubular.com/r/SRKkYrW4IJ
Written by Sean Behan on 11/14/2013
How To Fix ActiveRecord::ConnectionTimeoutError with Sinatra
If you get this error message
ActiveRecord::ConnectionTimeoutError could not obtain a database connection within 5.000 seconds (waited 5.001 seconds)
Try closing the connection after each request using "after" in Sintara.
# app.rb
after { A...
Written by Sean Behan on 11/09/2013
Open Files in TextMate 2 with A Single Click
To open files with a single click from the file browser inside of TextMate 2 run this command from the terminal
defaults write com.macromates.TextMate.preview fileBrowserSingleClickToOpen -bool true
And to turn it off
defaults write com.macro...
Written by Sean Behan on 11/04/2013
How to Create A Unix Timestamp or the Epoch in Python
It's a little convoluted. Seeing as it's a pretty common thing you use when programming computers one might think that there would be a quick and easy method for it. But from what I can tell there isn't. So here is a snippet that will give you a *nix Epoc...
Written by Sean Behan on 11/02/2013
Roll Your Own Session Based Flash Messaging w/ Sinatra
Session based flash messages are fairly common in web apps. They work well when you have a temporary status to report back to the user, such as successfully saving a form.
If you use Rails it comes with the Framework. If you are using Sinatra there ar...
Written by Sean Behan on 11/01/2013
How to Fix Line Wrap Bug in iPython Terminal on OS X Mavericks
There is annoying line wrap issue present after installing iPython on OS X Mavericks for the first time. The issue has to do with readline being missing. To fix the problem uninstall iPython, install readline and then install iPython.
pip uninstall ip...
Written by Sean Behan on 10/26/2013
Change the Default Controller Name in Rails Functional Tests
Rails will infer the controller you want to test from the class name of the test case. For example...
class PeopleControllerTest < ActionController::TestCase
end
will test the app/controllers/people_controller.rb.
To change this is trivial. Us...
Written by Sean Behan on 10/23/2013
How to Use RVM and POW with Ruby 2.0.0
In your project's root directory add a .ruby-version file and add the ruby version to the file
ruby-2.0.0-p247
Next source RVM in the .powrc file, also in your project's root directory.
source "$rvm_path/scripts/rvm"
rvm use `cat .ruby-versio...
Written by Sean Behan on 10/19/2013
A Couple of Usefule Snippets When Working with Textmate
Here is the snippet
f path/to/directory 'search string' | open_in_mate
This snippet (technically 2 snippets) will recursively scan the contents of files in a directory and then open all the files it finds in Textmate.
It's useful on large projec...
Written by Sean Behan on 10/18/2013
How To Pipe To A Ruby Command Line Application
You need to read from STDIN rather than parse command line arguments.
while $stdin.gets
puts $_
end
Written by Sean Behan on 10/17/2013
How To Write Your Own Time Comparison Function in Ruby Like time_ago_in_words Without Rails
# time_ago_in_words(Time.now, 1.day.ago) # => 1 day
# time_ago_in_words(Time.now, 1.hour.ago) # => 1 hour
def time_ago_in_words(t1, t2)
s = t1.to_i - t2.to_i # distance between t1 and t2 in seconds
resolution = if s > 29030400 # seco...
Written by Sean Behan on 10/17/2013
How to Boot Up Multiple Sinatra Applications at the Same Time with Foreman
Foreman is a process management gem for ruby applications. It is used in combination with a Procfile for configuration instructions.
A typical Procfile looks something like this
[name] : [script to execute]
Example Rack application Procfile
...
Written by Sean Behan on 10/15/2013
How to Render Partials with an Underscore in Sinatra
Sinatra doesn't have a method for rendering partials. It defers to the template language of your choice. For instance, if you're using ERB, it's as simple as
erb :'path/to/partial'
Rails has a nice convention of using an underscore to mark file...
Written by Sean Behan on 10/13/2013
How to Split a Large File Into Smaller Files on OSX or Unix
Use the split command.
split -l 1000 name-of-file output/directory
You can set the number of lines (the "-l" flag) to split on and also the location of where the split files should be saved. Note, the output directory must already exists....
Written by Sean Behan on 10/08/2013
How To Remove Duplicates From a Table with Postgres
Let's create a table that will hold some dummy data.
> create table fruits (id serial primary key, name varchar, color varchar);
> insert into fruits (name, color) values ('apple', 'red');
> insert into fruits (name, color) values ('ap...
Written by Sean Behan on 10/08/2013
How to cast a string of comma separated numbers into an array of integers for Postgres
If you have an string of numbers like
"1,2,3"
and you want to turn it into an array of integers you need to cast it into an integer array type.
"{1,2,3}"::int[]
This is commonly used together when grabbing a set using the ANY clause.
sele...
Written by Sean Behan on 09/26/2013
Using Grep To Find or Match All Links in an HTML Document
egrep -or "(http(s)?://){1}[^'\"]+" path/to/directory
You can further reduce to just return the images by piping again.
grep -r src views/ | egrep -o "(mailto|ftp|http(s)?://){1}[^'\"]+"
The -r flag is for a recursive directory scan....
Written by Sean Behan on 09/15/2013
Recursively Search Contents of a File with Grep
The -r flag is for recursive, meaning it will also look in sub directories. The -i flag is for case insensitivity, meaning WORD and word will both be found.
grep -ir "search term" directory/path
Written by Sean Behan on 08/29/2013
How To Enable IFrame Support on Heroku with Ruby on Rails and Sinatra
This actually has more to do with Rails and/or Sinatra than it does with Heroku. You have to enable IFrame support in your headers explicitly.
With Rails you can add this to your config/application.rb file
config.action_dispatch.default_headers = ...
Written by Sean Behan on 08/25/2013
How To Increase or Change the File Upload Size in the PHP ini file for Wordpress
You need to find which configuration ini file has been loaded by PHP. The easiest way to do this is to run the phpinfo() function from the command line.
php -r "phpinfo(); " | grep -i "loaded configuration file"
You should see something like...
Written by Sean Behan on 08/24/2013
How To Create Blurry Background Images Programmatically from the Command Line or with Ruby
Turn this
into this
You can use ImageMagick to make blurry images.
To install with Homebrew on OS X.
brew install imagemagick
After installing you can run from the command line
convert yourimage.png -channel RGBA -blu...
Written by Sean Behan on 08/24/2013
A Regular Expression to Generate Dash Separated Slugs AKA Pretty URLs
This regular expression matches non alphanumeric characters in a string.
r = /[^a-z0-9]{1,}/i
You can use it to create URL friendly slugs.
slug = "hello world!".gsub(/[^a-z0-9]{1,}/i, '-').downcase # => hello-world
In combination wit...
Written by Sean Behan on 08/22/2013
JSON::GeneratorError: only generation of JSON objects or arrays allowed
If you run into this error message try switching to an earlier version of ExecJs.
JSON::GeneratorError: only generation of JSON objects or arrays allowed
# Gemfile
gem 'execjs', '~> 1.4'
gem 'coffee-script'
gem 'sass'
...
Written by Sean Behan on 08/22/2013
How to Extract the Title From an HTML Page with Ruby
This snippet will make a request to this page and extract the title from the title tag.
require 'open-uri'
html = open('http://www.seanbehan.com/how-to-extract-the-title-from-an-html-page-with-ruby').read
title = html.match(/(.*)/) { $1 }
pu...
Written by Sean Behan on 08/22/2013
Testing current_user and Sessions with Sinatra and Rack Test
Assume you have your standard Sinatra application.
# app.rb
require 'sinatra'
configure do
enable :sessions
end
get '/' do
if session[:user_id]
"OK"
else
raise "NOT OK!"
end
end
To test this you need to make a re...
Written by Sean Behan on 08/22/2013
How To Use Rake to Run Your Test Suite with Sinatra
If you're using Sinatra and you want to use rake to run your test suite, you will need to create a Rakefile and put this in it.
require 'rake/testtask'
task :default do
ENV['RACK_ENV'] = 'test'
Rake::Task['test'].invoke
end
Rake::Test...
Written by Sean Behan on 08/22/2013
Deploying Wordpress on Heroku
> This post is out of date - Heroku officially supports PHP now w/ buildpacks
Heroku runs
Apache version 2.2.22
PHP version 5.3.10
Deploying Wordpress to Heroku requires that you throw the Wordpress source into a Git repository. So download th...
Written by Sean Behan on 03/02/2017
Installing Ruby with RVM without Xcode using CLANG
I am not using the full Xcode package on my laptop. Instead I'm using the command line tools, offered by Apple as a separate and much smaller install. I haven't had too many issues, aside from not being able to use the FileMerge program that ships with ...
Written by Sean Behan on 06/24/2012
How To Export A MySQL Database to JSON, CSV and XML with Ruby and the ActiveRecord Gem
It's trivial to export data from a mysql database with Ruby and ActiveRecord. All you have to do is establish a connection and define a class that represents the table.
require 'rubygems'
require 'active_record'
ActiveRecord::Base.establish_con...
Written by Sean Behan on 06/23/2012
How to Add Additional Sub Directories to the Default Rails Test:Unit File Structure
# Edit Rakefile in project root
#
# Add a new rake test task... E.g., rake test:lib, below everything else in that file...
# Alternatively, add a task in lib/tasks/ directory and plop in the same code
namespace :test do
desc "Test lib source"
...
Written by Sean Behan on 06/17/2012
How to Create a Date Time Snippet in Sublime Text 2 (Dynamic Signature with Time Stamp)
You'll have to create a new plugin. From the menu bar select
Tools > New Plugin
Copy the Python script from the signature.py file. Remember to replace your email address (it's example.com).
Save the file, signature.py, is fine. Next open up Prefer...
Written by Sean Behan on 06/17/2012
Transform Matching Text with Gsub in Ruby and Regular Expression
Here is a gist that demonstrates how easy it is to transform text using #gsub and a block with Ruby.
"Scs Epc Score".gsub (/scs|epc/i) { |i| i.upcase }
# => SCS EPC Score
For more helpful string extensions in Ruby check out our Ruby Gem on GitHub...
Written by Sean Behan on 06/17/2012
Color Output with Test:Unit, AutoTest and Ruby 1.9
If you are testing using Test:Unit (rather than RSpec) and you're using Ruby 1.9.* colorized output of your tests using Autotest will not be immediately available. Since, 1.9 comes with mini test the test/unit/ui/console/testrunner.rb script is not loaded...
Written by Sean Behan on 06/17/2012
How to Merge a YAML File Into a Single Hash in Ruby
require 'yaml'
# Nested YAML structure from something-nested.yml
#
# nested:
# key: value
# key_two: value_two
# Procedural Approach to building a single Hash from nested YAML data structure.
@yaml = YAML.load_file("something-nested...
Written by Sean Behan on 06/17/2012
Email Regex
Regular Expression that Matches Email Addresses:
/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b/
Written by Sean Behan on 06/17/2012
Vim Tips and Tricks
The following tips and tricks can be put into your .vimrc file
Remap jj to esc
imap jj <Esc>
Quickly leave edit mode and back to visual mode with jj. This is probably the fastest key combination possible and one of the most frequent key combinatio...
Written by Sean Behan on 06/17/2012
How to Upgrade RVM on Mac OS X
I had an old version of rvm installed and wanted to upgrade. So old in fact that the resource for upgrading no longer existed.
rvm update
just returned a 301, redirect.
Luckily, the following worked
# checks out from repo
rvm update --head
# will re...
Written by Sean Behan on 06/17/2012
Ruby Reload! Method in Non Rails IRB Sessions
I love the Rails reload! function when in the console. I need it in Irb. To get it back this is what I did. If you don't already have an .irbrc file in your home directory, just create it.
vim ~/.irbrc
or textmate if you prefer
mate ~/.irbrc
Add this...
Written by Sean Behan on 06/17/2012
How to Recover a Mistakenly Deleted Branch
Workflow
git checkout -b _new_branch_name
# do some work and commit changed
git checkout master
git branch -d _new_branch_name
# doh... i meant to merge first
Fortunately, you can easily recover from this mistake.
git reflog
395b1ea HEAD@{0}: checkout...
Written by Sean Behan on 06/17/2012
Aliasing Attributes in Ruby on Rails
Alias an attribute with alias_attribute method.
The first argument is the name for the new attribute, while the second argument is to identify the attribute that is already defined.
class User < ActiveRecord::Base
alias_attribute :username, :login
...
Written by Sean Behan on 06/17/2012
Rails 3 Config Auto Load Paths in Application.rb
In Rails 3 files in lib/ are no longer loaded by default. It's a snap to auto load these classes by adding the following line to config/application.rb
config.autoload_paths += %W(#{config.root}/lib)
This is commented out around line 16. Either rep...
Written by Sean Behan on 06/17/2012
How To Get A List of All Registered Mime Types in Rails
When mime types are registered they are placed in a hash constant EXTENSION_LOOKUP in the module Mime. For reference, the file with the relevant code is in rails/action_pack/lib/action_dispatch/http/mime_type.rb available on Github at https://github.com/r...
Written by Sean Behan on 06/17/2012
Git Feature Branch Naming Strategy
There are only two hard things in Computer Science: cache invalidation and naming things.
-- Phil Karlton
Typically, we have three main branches at any given time in a project lifecycle.
master, development and staging.
Master is production ready code, d...
Written by Sean Behan on 06/17/2012
My First Ruby Gem: Hashed_Attributes
I just wrote and released my first Ruby Gem, Hashed Attributes https://rubygems.org/gems/hashed_attributes. It is a very simple ActiveRecord extension for saving variables through a serialized hash. The Gem will let you declare getter and setter methods t...
Written by Sean Behan on 06/17/2012
Rails Send_File in Production Delivers an Empty File
If you're running Rails in production it will by default be configured to let apache or nginx send files for you. If you're handling file downloads yourself with send_file
send_file("path/to/file.txt")
you will notice that the downloaded files are empty...
Written by Sean Behan on 06/17/2012
Git Untrack Already Tracked Files
To remove files that are currently being tracked by git, you have to remove them from the "cache". Note, doing this will NOT delete the file on your local machine. It will still be there but not be tracked.
git rm -r --cached supersecretpasswords.txt
Yo...
Written by Sean Behan on 06/17/2012
Rails Find All by Birthday: How to Find Upcoming Birthdays with ActiveRecord
There are a few ways to solve this problem. However, I think the easiest is to cache the day of the year that the user is born on as an integer. If stored alongside the timestamp we can quickly get a list but properly handle the full birthday elsewhere, s...
Written by Sean Behan on 06/17/2012
Git: How to Delete a Branch with an Invalid Name
If you've named a branch beginning with two dashes "--", you're sort of in trouble because git interprets your branch name as a switch/flag. You can skip switches all together
by supplying two dashes before your branch name
git branch -d -- --index_for_...
Written by Sean Behan on 06/17/2012
Backup and Rotate MySQL Databases Simple Bash Script
Make a directory ( it can anywhere ) called baks/mysql
mkdir -p /baks/mysql
Create a file (it can be anywhere) called /root/mysql_backups.sh and put this script in it
#!/bin/bash
# modify the following to suit your environment
export DB...
Written by Sean Behan on 05/16/2017
Ruby Rand Range
I assumed that rand would take a range as an argument. Something like rand(10..20), generating a random number between 10 and 20. Seems like you'd do this fairly often when working with random numbers and therefore, included. However, it doesn't work. But...
Written by Sean Behan on 06/17/2012
Link to jQuery Source from Google's CDN
https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js
That is the link to the jQuery source hosted by Google on their CDN. It's probably already cached on client machines so it should be as fast as is possible! You can read more/use other Java...
Written by Sean Behan on 06/17/2012
Simple String Concatenation of a Collection Written as a Helper for Rails
At Railsconf last week I took Greg Pollack's online course Rails Best Practices. The interface is gorgeous and the instructions are excellent. One of the lessons involved taking a partial and moving it into a helper. I was reminded how difficult such a si...
Written by Sean Behan on 06/17/2012
How to Copy and Paste to/from the Global Register with Tmux on Mac OS X
Using the system clipboard with tmux on OS X is broken. I really like tmux but having copy and paste is kind of important for me. Here is my attempt to get it back with a simple bash script until I find something better. The approach is to take a named pi...
Written by Sean Behan on 06/17/2012
Reusing Scopes (Formerly Named_scope) In Rails 3
You can easily chain scopes together in your models.
class Article < ActiveRecord::Base
scope :ordered, order('position ASC')
scope :published, ordered.where('published = ?', true)
scope :for_homepage, published.limit(3)
end
Article.for_homepage...
Written by Sean Behan on 06/17/2012
Installing MatPlotLib on OS X for Python Version 2.6.1 with PIP and VirtualEnv
If you thought you had installed matplotlib only to find this
File "/Library/Python/2.6/site-packages/matplotlib-0.91.1-py2.6-macosx-10.6-universal.egg/matplotlib/numerix/__init__.py", line 166, in
__import__('ma', g, l)
File "/Library/Python/2.6/...
Written by Sean Behan on 06/17/2012
Installing Ruby on Rails 3, MySQL, Git, Ruby Enterprise Edition, Passenger (Mod_Rails) on Ubuntu with Rackspace Cloud.
Short and sweet. Here all the commands I run in this order to set up a brand new box. It usually takes about 10 - 15 minutes on a 256 MB RAM instance. Compiling Ruby Enterprise Edition, which is super easy, will take the most amount of time. It will seem ...
Written by Sean Behan on 06/17/2012
Rails 3 disable_with Does Not Work with Ajax Remote Form_for
It appears that the :disable_with option on the submit_tag form helper method does not behave as expected with remote forms. I'm not sure if this is a bug or not. But the fix is pretty straight forward, but perhaps a little difficult to trouble shoot. Usi...
Written by Sean Behan on 06/17/2012
How to Remove Your Last Git Commit
Remove your last commit (if you haven't pushed yet)
git reset --hard HEAD~1
To see changes that have been committed and their position in HEAD
git reflog
And to undo your previous reset and advance the cursor to the reference immediately behind the cu...
Written by Sean Behan on 06/17/2012
Execute Javascript When Using Link_to_function To Include a Partial in Rails
If you use the link_to_function to replace content in a div with content from a partial, any javascript that you include in the partial will not be executed. It is instead included, but will do nothing. Obviously, this isn't the desired behavior. Why woul...
Written by Sean Behan on 06/17/2012
Rails Select Tag and Onchange Event Calling a Remote Function with Default Option Selected
Here is a little code snippet that will fire off a request to update_client_path when you change the select field. This stands alone, rather than being apart of a larger form. The Client::CATEGORY argument is a hash, which I populated manually in my Clien...
Written by Sean Behan on 06/17/2012
Ruby Enterprise Edition and Passenger ./script/console production fails and instead returns Loading production environment (Rails 2.3.5) Rails requires RubyGems >= 1.3.2. Please install RubyGems and try again: http://rubygems.rubyforge.org
After installing Ruby Enterprise Edition, REE, and Passenger on Ubuntu you may see this error message when you run script/console for the first time
./script/console production
# =>
Loading production environment (Rails 2.3.5)
Rails requires RubyGems >=...
Written by Sean Behan on 06/17/2012
How Many Gigs of RAM Are On My Server?
How much memory is on my linux server? Run the free command
free -g
total used free shared buffers cached
Mem: 2 1 0 0 0 1
-/+ buffers/cache: 0 1
Swap: ...
Written by Sean Behan on 06/17/2012
Have Git Email Committers After Pushes
You need a Mail Transfer Agent MTA on the server. The easiest way is to install Sendmail, which Git uses by default.
apt-get install sendmail
Remember that /etc/hosts file needs the ip address to map to the domain name your sending mail from
# vim /et...
Written by Sean Behan on 06/17/2012
Setting Up Users, Permissions and Groups for SSH Access to a Shared Git Repository
If you are having permission problems using git, such as
error: insufficient permission for adding an object to repository database ./objects
There are a couple thing you can do to remedy the situation, before moving to a full on git server like gitosis....
Written by Sean Behan on 06/17/2012
Installing and Using Rvm on Mac OS X, Creating Gemsets and Reverting to Original Environment
What is RVM and why should you use it? RVM is a Ruby interpreter, version management tool. In short, it enables you to switch between different versions and releases of Ruby (for instance, version 1.8.6, 1.8.7, jruby 1.9.2, ruby enterprise edition) on the...
Written by Sean Behan on 06/17/2012
Renaming Routes in Rails 3 with :As and :Controller
Renaming routes in Rails 2.* is straight forward. It goes something like this.
## config/routes.rb
map.resources :users, :as => :members
This will give you users_path and form_for(User.new) helpers, for instance, mapping the url to /members instead of ...
Written by Sean Behan on 06/17/2012
Combat Spam with the Akismet Class for Ruby
Here is the Akismet.rb class, written by David Czarnecki. I've seen several tutorials online using this class, however, the class isn't available at David's blog. So... I reposted it here and at the pastie link below
http://pastie.org/1150693
...
Written by Sean Behan on 06/17/2012
Running Gem Server to View Docs for Ruby Libraries on Localhost
gem server
will boot up documentation on port 8808 by default pass it the -p flag followed by the port number to change.
gem server -p3000
Written by Sean Behan on 06/17/2012
Uploading Files with Curl
curl -i -F name=test -F filedata=@localfile.jpg http://example.org/upload
Courtesy of http://ariejan.net/2010/06/07/uploading-files-with-curl/
Written by Sean Behan on 06/17/2012
Collection Select Helper and OnChange Event in Rails
Given a collection of Active Record objects, you may use the collection_select helper method to produce a select form field. You need to pass in a number of arguments to the helper function.
1) object - your model object used in the collection
2) method ...
Written by Sean Behan on 06/17/2012
Repost
This post is inspired by
http://pupeno.com/blog/really-resetting-the-database/#comment-1179. But as my blog mostly serves as a reference for my future self, I'd like to reprint this little snippet of code here as well.
namespace :db do
desc "Crush a...
Written by Sean Behan on 06/17/2012
Rounded Corners with CSS
.rounded_corners {
-moz-border-radius: 20px;
-webkit-border-radius: 20px;
-khtml-border-radius: 20px;
border-radius: 20px;
}
Written by Sean Behan on 06/17/2012
Select Distinct in Rails with Active Record
User.find :all, :select => "DISTINCT occupation"
Written by Sean Behan on 06/17/2012
A List of Every High School in the United States in Pipe Delimitted Form (2005)
Here is a text file containing every high school in the United States(2005), including city, state, zip code and high school name.
us_high_schools_pd
Written by Sean Behan on 06/17/2012
The Context of Markup vs Expressions of Equality in Determining the Meaning of Angled Brackets
In the Wordpress editor (html mode) you'll need to become friends with < and > if you plan on showing any code (php, html... xml, most languages actually) that readers will want to understand.
I never thought about it, but assumed that the lt and...
Written by Sean Behan on 06/17/2012
Simple Activity Stream Implementation in Rails
There are many ways to tackle the Facebook style activity stream feature for your app. The simplest approach, which you can tack on at almost any moment, is what I'll describe here. You don't have to create a new model for news feed items or create any po...
Written by Sean Behan on 06/17/2012
Scope Routes/URLs By Username (like Twitter) in Your Rails Application
There are a few things that need to be taken care of before you can get this to work. The first thing (although, any of the following steps can be done in any order) to take care of involves your User model. You need to override the to_param method, so th...
Written by Sean Behan on 06/17/2012
TODO and Custom Annotations in Rails Applications
While writing software it's common to leave comments for your future self. For instance, if you have written some code but realize that it should be refactored to be more efficient, you may place something along the lines of "TODO: change active record fi...
Written by Sean Behan on 06/17/2012
Load All ActiveRecord::Base Model Classes in Rails Application
Here is a simple rake task which will instantiate all of your Active Record models, provided that they are located in the RAILS_ROOT/app/models directory. Interestingly, all plugin models are instantiated by default when you run the task, for instance, if...
Written by Sean Behan on 06/17/2012
How Beautiful is Ruby?
Working with Ruby and in particular Rails, it's easy to take the beauty inherent in the language for granted. I mean look at this code. If you read it aloud to yourself, it reads like an english sentence that any non programmer can understand.
Forum.cate...
Written by Sean Behan on 06/17/2012
Deploying to Dreamhost
Remember to include the host declaration in the database.yml file when you deploy to Dreamhost. Dreamhost does not use "localhost" which is typically the default setting when using the mysql adapter and developing locally or even on a small site.
At lea...
Written by Sean Behan on 06/17/2012
How to Import/Export Your Wordpress Blogroll... er, Your Links
It's not immediately apparent how to import/export the links in your Wordpress blogroll. One would expect that the import/export tool, used to backup/restore Wordpress posts and pages would handle this functionality as well. But the import/export tool has...
Written by Sean Behan on 06/17/2012
How to Check if the Current Logged In User can Edit a Course in MOODLE Using the Has_capability Function
After an hour of fruitless searching through the docs and forums, I finally found an answer to my simple question, of course buried in the depths of the shark infested, murky water that is the Moodle code base .
How do I check if a user is a course creat...
Written by Sean Behan on 06/17/2012
Moodle's Most Important Function Gets No Attention
Arguably the most important function in the Moodle API, is the create_course function. One would think... after all Moodle is an LMS. Courses are the bread and butter for course management platforms, right? Taking a look at the function in the course/lib....
Written by Sean Behan on 06/17/2012
Recursively Zip Up a Directory while Excluding Certain Files Based on File Extension Type
In the example below, I'm going to zip up a directory that includes images in both PNG and PSD file formats. However, I want to exclude the PSDs because they are huge!
zip -r my-compressed-dir-without-psd.zip directory-to-zip -x '*.psd'
Written by Sean Behan on 06/17/2012
Uncompress A Bz2 File Using Tar Command
Uncompress a bz2 file using tar command
tar --use-compress-program bzip2 -xvf your-file-to-uncompress.tar.bz2
@source http://www.kde.gr.jp/help/doc/kdebase/doc/khelpcenter/faq/HTML/bzip2.html...
Written by Sean Behan on 06/17/2012
Get Child Categories of Parent Category on Single Post in Wordpress
I was hoping to find a function in the Wordpress API, that goes something like this...
the_child_categories("Vermont");
// print Burlington, Brattleboro... etc if this post has any child categories of Vermont
But I could not. The result that I did ...
Written by Sean Behan on 06/17/2012
How To Flush Your Permalink Structure in Wordpress When Using Taxonomies ...or Wordpress Taxonomies Not Working Instead I See A 404 Page
I didn't know this, but because of a linking problem using custom taxonomies in Wordpress, I was forced to find out. If you create a new taxonomy, it will not work immediately on the front facing end. Your users will be greeted by a 404, page not found in...
Written by Sean Behan on 06/17/2012
Render Partial if File Exists
If you ever want to render a partial but don't want an error thrown you can either check for the existence of the file first
params[:controller]+"/sidebar" if File.exists?(RAILS_ROOT+"/app/views/"+params[:controller]+"/_sidebar.html.erb") %>
or you ca...
Written by Sean Behan on 06/17/2012
My Review of Moodle 1.9 Extension Development
I wrote a review for Joseph Thibault's Moodle News on extension development for Moodle. The book is quite good and I think an essential resource for anyone wanting to develop in Moodle. The book focuses on plugin development, but it will also give you an ...
Written by Sean Behan on 06/17/2012
NO Table Cell Spacing Please
Remove cell padding on a table you add the cellspacing attribute and set it to "0". Is there a better way to do this with straight up CSS? Nothing seems to work...
<table id='my-favorite-table' cellspacing="0" >
...
Written by Sean Behan on 06/17/2012
Offset an Element with Relative Position Property with CSS Without Taking Up Any Space in the Document
Using CSS positioning it's possible to offset an element and collapse its width and height where it would normally appear. Wrapping the content in an absolute positioned element, the space that the element would normally take up is collapsed.
<div st...
Written by Sean Behan on 06/17/2012
Natural Dog Training Buzz
NDT Buzz is a companion news site to Natural Dog Training.
News and information about Natural Dog Training is generated on the web from many different sources. Blogs, tweets and comments are aggregated using the Feedzirra Ruby Gem. The site lets NDT use...
Written by Sean Behan on 06/17/2012
Natural Dog Training
Natural Dog Training uses Wordpress to run a blog and content management system.
Custom design, theme and plugin development
Written by Sean Behan on 06/17/2012
Launch Photoshop (Or Any App) From The Command Line on Mac OS X
I often find myself coding with the terminal open. Cding around a web app project I usually end up at some point launching Photoshop. Either to touch up or work on a psd, png, jpg ...etc. I fire up Photoshop and then navigate to the app's public directory...
Written by Sean Behan on 06/17/2012
Programmatically Turn Off Comments in Wordpress with Filter
To turn comments off programmatically with a filter in Wordpress, you can set the post object's comment_status variable to "closed". Call the filter at some point after the post is loaded but before the comments are rendered. This is a hack, but I haven't...
Written by Sean Behan on 06/17/2012
Intercepting the Wordpress Loop with Pre_get_posts
#deprecated (see http://codex.wordpress.org/Function_Reference/query_posts#Post_.26_Page_Parameters)
Using the "pre_get_posts" filter you can intercept the Wordpress loop and override or set attributes in the "$query" object. This is useful because you c...
Written by Sean Behan on 06/17/2012
Thematic Function Reference
I could not find a listing of all thematic theme functions for Wordpress online. So the following is just a recursive grep of the thematic directory.
grep -rh "function thematic_" *
Each function needs to prepended with "thematic_" when adding as a actio...
Written by Sean Behan on 06/17/2012
Very Simple Breadcrumb Navigation in Rails with Before_filter
This may not be the ideal solution. This just manages request.referers in a session variable, then looping over each unique path prints a link to the screen. It's more of a "history" than a hierarchy for resources in an application. It is however, pretty ...
Written by Sean Behan on 06/17/2012
Yield a Block within Rails Helper Method with Multiple Content_tags Using Concat
To clean up some repetitive html coding in views, pass a block of text to a helper function which will wrap it for you the same way, each and every time. For example, I have a 'help' link which will toggle the display of a block of text if a link is click...
Written by Sean Behan on 06/17/2012
Nesting Resources in Rails Routes.Rb with Namespaces
When I have a controller that takes more than one has_many argument, I think about creating a namespace. This way I may still use my forums, pages controllers w/out needing any conditional logic, testing for the presence of :course_id in the params hash.
...
Written by Sean Behan on 06/17/2012
Rake DB Everything, Dump, Destroy, Create, Load
I'm a big fan of the yaml_db plugin. But I don't like running rake db:data:load, only to find that my db columns mismatch my model attributes, thus aborting the data import task. To quickly add/remove columns/attributes from a model and rebuild the datab...
Written by Sean Behan on 06/17/2012
Carrier Email Addresses for Sending SMS over Email
Just for reference, here are the carrier email addresses for sending email as an SMS. Look up the carrier for the phone in question, then send an email in this format [telephonenumber]@[carrier-name.com]
Carrier Email to SMS Gateway
Alltel [10-digit p...
Written by Sean Behan on 06/17/2012
Why are PHP5 Namespaces Defined Using a Backslash?
Why are PHP namespaces defined using a backslash? It looks ugly. Unless of course, there is a good reason for the "\"? Does this namespaced code run more efficiently on Windows?
Since namespaces are new in PHP5 why not take the opportunity to use them wh...
Written by Sean Behan on 06/17/2012
Very Basic Git Workflow
Very, very basic git workflow
git pull
git branch dev_branch
git checkout dev_branch
#make some changes
git checkout master
git merge dev_branch
git branch -d branch_to_delete
git push
Written by Sean Behan on 06/17/2012
Using Module Mixins to Extend Classes and Objects in Ruby
The module and class below demonstrate how to use instance methods and class methods from "module mixins". The thing to remember is scope. For instance, to use class methods within instance methods you need to call them from the class itself. This is acco...
Written by Sean Behan on 06/17/2012
Installing RedMine PM Software on Apache with Phusion and REE and Seeing a 404 Page Not Found Error on Installation
If you follow the instructions on how to install the Rails Redmine PM Software (available here) and are using Apache with Passenger (REE), you need to delete the .htaccess file that is kept in RAILS_ROOT/public directory. Otherwise you'll see a 404 page n...
Written by Sean Behan on 06/17/2012
Change database column names for form validations in Rails
When you use validations in Rails, db column names are used as 'keys' for error messages. This is usually the preferred way to go about it because this maps nicely to the form fields. However, if you use a virtual attribute this may not be the case. For e...
Written by Sean Behan on 06/17/2012
Active Record Find Methods
Active Record find methods for selecting range from http://charlesmaxwood.com/notes-from-reading-activerecordbase/
Student.find(:all, :conditions => { :grade => 9..12 })
return a range
Student.find(:all, :conditions => { :grade => [9,11,12] })
will retu...
Written by Sean Behan on 06/17/2012
Defining Application Constants for Ruby on Rails Application
The best place to keep application constants which are environment specific is in config/environments directory. For instance...
# in RAILS_ROOT/config/environments/development.rb
APP_DOMAIN = "localhost"
# in RAILS_ROOT/config/environments/production.rb...
Written by Sean Behan on 06/17/2012
Adding Public/Private Key Pairs on Mac OS X and Ubuntu for Passwordless Remote SSH Sessions
On your local machine cd into the .ssh directory in your home "~/" directory. If it doesn't exist you can create it with "mkdir ~/.ssh". Next generate your public/private keys and copy the public key to the remote server.
cd ~/.ssh
ssh-keygen ...
Written by Sean Behan on 06/17/2012
Hacking Rails Plugins
Using the Acts as Taggable On plugin to add categories to a model class, I wanted to override the to_param method and place the name attribute in the url. The plugin, installed as a gem, source shouldn't need to be hacked in order to accomplish this. The ...
Written by Sean Behan on 06/17/2012
Setup Wildcard Subdomain on Localhost for Development Work without /Etc/hosts TomFoolery
Step 1.
Open up your browser and visit http://www.hexxie.com. You can also go to anything.hexxie.com and everything.hexxie.com, which will resolve to your local machine (assuming it's localhost at 127.0.0.1).
How it works
Super simple. I just pointed hex...
Written by Sean Behan on 06/17/2012
Onchange Event Fired from Select Field in Rails Form
In the view there is a regular Rails form and a javascript function that will be triggered when the country select field is changed. The javascript function will make an ajax request to the country_select url with the country code passed as the id variabl...
Written by Sean Behan on 06/17/2012
Rails Plugin Acts as Taggable on Steriods
You can download it here http://github.com/suitmymind/acts-as-taggable-on-steroids as well as read usage info (which is for the most part reprinted here).
./script/plugin install http://svn.viney.net.nz/things/rails/plugins/acts_as_taggable_on_steroids
....
Written by Sean Behan on 06/17/2012
Rails Helper to Remove Leading Zero in 12 Hour Time Format
I can't find a strftime() format that will output the hour without the leading zero. For instance 6:20 will be instead 06:20. This just looks a little sloppy. I created a datetime.rb intializer which will contain custom datetime formats for my applicatio...
Written by Sean Behan on 06/17/2012
Extending Rails Form Builders
Extending forms in Rails is simple and will greatly reduce the amount of code in your views. This example is taken right from the Agile Web Development book on Rails(2.1.*) with one minor tweak. I want to pass a label argument along with the field name so...
Written by Sean Behan on 06/17/2012
Ruby Strftime Day Without the Leading Zero
%e # rather than %d
Time.now.strftime("%e")
Written by Sean Behan on 06/17/2012
Install and Serve a Rails Application from PHP Subdirectory Using Apache, Phussion Passenger and Ruby Enterprise Edition
Here is how to install a Rails application out of a subdirectory (rather than as a subdomain) with the Apache web server(Apache2). In this example I'm going to use my own blog which is a Wordpress installation and serve a Rails application from the subdir...
Written by Sean Behan on 06/17/2012
Using the PHP Mail Function with Additional Headers
Pass a fourth parameter to the mail() function with the header information.
<?php
$to = "jane@example.com";
$subject = "Hello World!";
$body = "This will be sent from email-addr@example.com";
$headers = "From: email-addr@example.com\r\nX-Mailer: php";...
Written by Sean Behan on 06/17/2012
Dump MySQL Database without Drop Table Syntax
Output .sql file for MySQL but without the drop table syntax before table name use the --skip-add-drop-table flag
mysqldump -u root -p database_name --skip-add-drop-table --skip-lock-tables > database_name.sql
Written by Sean Behan on 06/17/2012
Generate MySQL Datetime Type Using PHP Date() Function
If you want to insert a datetime that matches the default mysql datetime type format use this
date('Y-m-d H:i:s');
Written by Sean Behan on 06/17/2012
PHP Paypal IPN Script
Simple script for posting a valid response back to Paypal service after a sale is completed using the Paypal Instant Checkout payment method.
<?php
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
foreach ($_POST as $k...
Written by Sean Behan on 06/17/2012
Listing Files and Directories with PHP
Listing all files and directories using PHP 5.
<?php
$files = array(); $dir = dir(".");
while(false!==($file=$dir->read())):
if(($file{0}!=".") && ($file{0}!="~") && (substr($file, -3)!="LCK")
&& ($file!=basename($_SERVER["PHP_SELF"]))):
...
Written by Sean Behan on 06/17/2012
Highlight String in PHP
Function for highlighting text/strings in PHP.
$content = file_get_contents("http://php.net/");
print highlight("PHP", $content);
function highlight($match, $string){
return str_ireplace($match, "<span style='background:yellow'>$match</span&...
Written by Sean Behan on 06/17/2012
Absolutize Relative Links Using PHP and Preg_Replace_Callback
I was in the market for a simple php script to replace hrefs with their absolute paths from scraped web pages. I wrote one myself. I used the preg_replace_callback function so that I could pass the parsed results as a single variable.
<?php
$domain =...
Written by Sean Behan on 06/17/2012
Hello Rack
What is Rack?
Rack provides a minimal, modular and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in the simplest way possible, it unifies and distills the API for web servers, web frameworks, and sof...
Written by Sean Behan on 06/17/2012
The survey for people who make websites
I took the survey!
Click here to take it →
Written by Sean Behan on 06/17/2012
Placing an Authenticity Token in a Rails Form
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
Written by Sean Behan on 06/17/2012
Managing Timestamps in MySQL with a Trigger
MySQL doesn't support having two columns with time stamping on both initialization and/or on updating at the same time. It would be nice to be able to do *this* where the created_at column gets the current_timestamp on initialization and the updated_at ge...
Written by Sean Behan on 06/17/2012
Grab a Twitter Status without the Twitter API
Quick and dirty way to grab the users status messages without having to go through the twitter api (not having to authenticate that is). You can grab the RSS feed and indicate the number of statuses returned with the count param. I wrote this function for...
Written by Sean Behan on 06/17/2012
Updating Your Twitter Status with cURL and a Bash Function
I'm usually at the command line so I wrote a little a bash function so that i can type
tweet this is really neat but kind of pointless
and it will update my twitter status! some characters trip it up but in general it's useful for most of my tweets. The...
Written by Sean Behan on 06/17/2012
Mod_Python and Web.py on Ubuntu
Download
First install mod_python for Apache and then restart/reload the server.
apt-get install libapache2-mod-python
/etc/init.d/apache2 force-reload
apache2ctl restart
Next grab the web.py framework from webpy.org. You can grab the tar or use easy_in...
Written by Sean Behan on 06/17/2012
Ruby on Rails, jQuery and YUI API Docs Available as Mac OS X Dictionary Binaries
I came across an awesome tool this morning. Priit Haamer has chunked Ruby on Rails, jQuery, and some of YUI documentation into native Mac OS X dictionary binaries. This lets you search those API docs from Spotlight, TextMate, any application that uses the...
Written by Sean Behan on 06/17/2012
My First Data Visualization McCain V. Obama Election Results
Here is my first data visualization. I used the Processing programming language and an SVG map of the United States.
...
Written by Sean Behan on 06/17/2012
Reading, Writing, Removing Files and Directories in Ruby
These aren't all of them, but I think they are some of the most useful.
# making a directory in another directory that doesn't yet exist...
FileUtils.mkdir_p '/path/to/your/directory/that/doesnt/exist/yet'
# recursively remove a directory and the conten...
Written by Sean Behan on 06/17/2012
Adding RSS Graffiti to my Facebook Page
I added the RSS Graffiti application to my Facebook account. It's a nifty app that lets you add any valid Rss/Atom feed to your profile (includes publishing to your wall) and to your pages.
Written by Sean Behan on 06/17/2012
Accessing Links in Nested TD Cells with Prototype
There must be a better way to do the following with PrototypeJS. I want to loop over nested links inside of table td cells and apply a class to the row that the link is in when the link is clicked. If a user clicks on another link the class will be remov...
Written by Sean Behan on 06/17/2012
How to Install a Ruby Package without Ri or RDoc
gem install --no-rdoc --no-ri rails
Written by Sean Behan on 06/17/2012
Descending Sort By in Model For Active Record Hash on Created_at attribute
If you have a couple collections from the database and you want to sort it without the help of Active Record, take a look at the sort_by method on Array type. I've used this before when I have a couple of collections which are slightly different but I nee...
Written by Sean Behan on 06/17/2012
Output Logger and SQL to the Rails Console in Development Mode
If you want to take a look at the SQL being generated by active record while your using the console, you can either type this into the console when it loads
ActiveRecord::Base.logger = Logger.new(STDOUT)
Or you can add it to your environment so that it'...
Written by Sean Behan on 06/17/2012
TinyMCE Rich Text Editor: HELLO EDITOR Plugin Tutorial and Example
I wanted to create a button for the TinyMCE Rich Text Editor for Wordpress. It was tough to find good docs on the subject. There are a couple of useful posts out there but in general I found them lacking.
http://codex.wordpress.org/TinyMCE_Custom_Buttons...
Written by Sean Behan on 06/17/2012
Disk Usage Information on Mac OS X
Get disk usage information about the Desktop
$ du -h -d 0 Desktop
14G Desktop
Information about how much free space is available on computer
$ df -lh
Filesystem Size Used Avail Capacity Mounted on
/dev/disk0s2 111Gi 109Gi 2.3Gi 98% /
...
Written by Sean Behan on 06/17/2012
Working with Branches in Git
Show all the branches
git branch
Create a new branch
git branch my_experimental_feature
Use that branch
git checkout my_experimental_feature
Pushing the new branch to a remote server
git push origin my_experimental_feature
Pulling that branch down...
Written by Sean Behan on 06/17/2012
A Through Z
How to print the alphabet in Rails very easily.
("A".."Z").each {|letter| link_to letter, "/#{letter"}
"A".upto("Z") {|letter| link_to letter, "/#letter"}
Written by Sean Behan on 06/17/2012
Fun with Apache2 - httpd not running, trying to start (98)Address already in use: make_sock: could not bind to address 0.0.0.0:80 no listening sockets available, shutting down
Have you ever gotten this error message when trying to (re)start Apache
httpd not running, trying to start
(98)Address already in use: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
If you are running with ...
Written by Sean Behan on 06/17/2012
Rails Paperclip Plugin Options for Attaching Files
I usually change some of the default settings when I use the Paperclip plugin. For most of my projects I don't like having separate directories for each image that is uploaded. I prefer, in this instance, to put avatars of different sizes together under o...
Written by Sean Behan on 06/17/2012
Python Zlib Compress DeCompress
import zlib
regular_string = 'this is my string'
compressed_string = zlib.compress(regular_string)
decompressed_string = zlib.decompress(compressed_string)
print compressed_string
print decompressed_string
Written by Sean Behan on 06/17/2012
Build Your Own Calendar in Rails without any Plugins in less than 10 lines of Ruby Code
There are a number of terrific calendar plugins for Rails. But it's almost as easy, if not easier, to implement your own calendar.
The steps are pretty simple. First get the @beginning_of_month and @end_of_month and iterate over the days in between. In t...
Written by Sean Behan on 06/17/2012
Override to_param method in model to get pseudo permalinks without any work
There are a number of permalink plugins for Rails, http://www.seoonrails.com/even-better-looking-urls-with-permalink_fu, is a good one that I've used before. However, this involves informing the model class (has_permalink :title), adding a route, using t...
Written by Sean Behan on 06/17/2012
Date and Time Helpers in Rails
Just for reference http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#M001695
This post was created about ago
Written by Sean Behan on 06/17/2012
Installing Scala on Mac OS X Leopard
I followed the instructions from here http://arvinderkang.com/2009/09/01/installing-scala-on-snow-leopard/ but I used version 2.7.6 (rather than .5) I installed scala under /usr/local/scala so I had to include it to my path. Type
vim .bash_profile
expor...
Written by Sean Behan on 06/17/2012
Cool Conditional Syntax in Ruby (on Rails)
Ruby is beautiful
@posts =
if true
Post.all
else
[]
end
Simply elegant!
Written by Sean Behan on 06/17/2012
Acts_as_versioned Rails Plugin
Versioning models with the acts_as_versioned plugin
cd rails/app
./script/plugin install git://github.com/technoweenie/acts_as_versioned.git
./script/generate model post title:string body:text
In your model
class Post < ActiveRecord::Base
acts_as_ve...
Written by Sean Behan on 06/17/2012
Regular Expression for finding absolute URLs
Regular Expression for finding absolute URLs in a bunch of text... like a log file.
/(http:(.*?)\s)/
Written by Sean Behan on 06/17/2012
Manage Fixtures with Yaml DB Plugin for Rails
Get the plugin like so...
script/plugin install git://github.com/adamwiggins/yaml_db.git
This command will dump your data
rake db:data:dump
And load it back
rake db:data:load
Beautiful :) More info here
http://blog.heroku.com/archives/2007/11/23/yam...
Written by Sean Behan on 06/17/2012
Send Mail in Ruby with a Pony
Great little gem that let's you quickly and easily send out mail from your ruby scripts.
gem install pony
require 'rubygems'
require 'pony'
Pony.mail :from=>"me@example.com", :to=>"you@example.com", :subject=>"hello", :body=>"world"
Written by Sean Behan on 06/17/2012
Install do_mysql Ruby Gem on Mac OS X
I ran into the same problem when installing mysql gem for Rails development. This fix worked for me http://seanbehan.com/programming/fixing-mysql-for-rails-2-2-development-on-mac-os-x/
The same thing works with the data objects gem. Just specify the path...
Written by Sean Behan on 06/17/2012
Installing Redis Server and Client on Mac OS X and Ubuntu
wget http://redis.googlecode.com/files/redis-0.900_2.tar.gz
tar xzvf redis-0.900_2.tar.gz
cd redis-0.900
make
mv redis-server /usr/bin/
mv redis-cli /usr/bin/
Written by Sean Behan on 06/17/2012
Installing Monk on Ubuntu with Ruby Gems
Installing monk like this will fail
gem install monk
You'll need to install the wycats-thor gem first with this command
gem install wycats-thor -s http://gems.github.com
Written by Sean Behan on 06/17/2012
Manage Sinatra Server in Development Mode with Shotgun
Sinatra won't reload your files. So if you're developing your app and want to see any changes made in the browser, install the shotgun gem.
gem install shotgun
You can then use shotgun to run your server
shotgun your_sinatra_ditty.rb
Presto, your ditt...
Written by Sean Behan on 06/17/2012
Deploy Sintra App on Ubuntu Using Apache2 and Phusion Passenger Module
Check it out http://sinatra.seanbehan.com/
This assumes Apache2 and the Phusion Passenger module have already been installed. If not you can get up to speed w/ this resource http://seanbehan.com/ruby-on-rails/new-ubuntu-slice-apache-mysql-php-ruby-on-rail...
Written by Sean Behan on 06/17/2012
Double Click Event Using Prototype Javascript Framework
Super simple to get double click "desktop" like functionality out of Prototype! For some reason, googling it doesn't yield many useful results. http://www.google.com/#hl=en&q=double+click+in+prototype+javascript&aq=f&oq=&aqi=&fp=peEfEjG9pWY :(
Anyway, he...
Written by Sean Behan on 06/17/2012
Change default ssh port number on Ubuntu
Login as the root user or as a user that can execute sudo commands.
#open this file for editing...
vim /etc/ssh/sshd_config
Find the line that reads
Port 22
Change this to an different and an available port number...
Port 8000
Next reload ssh
/etc/...
Written by Sean Behan on 06/17/2012
Using sendmail to send mail on ubuntu box
I normally install postfix for my MTA. However, I've never really used sendmail so I'd decide to give it a whirl for a new application I'm working on. I don't use it for anything but handling the mail that the application needs to send out, like new user ...
Written by Sean Behan on 06/17/2012
Problem slash Bug in Rails with attr_accessor and Datetime Select Fields
Looks like there is a problem with using the attr_accessor method with datetime form fields http://dev.rubyonrails.org/ticket/8983 In Rails 2.3.2, for me at least, the problem seems to be popping up again. While trying to process a date for credit card v...
Written by Sean Behan on 06/17/2012
Trouble Using Attr_Accessor in Rails Models and Forms
You might use the attr_accessible method to create getters and setters for a class that has attributes which don't map directly to corresponding fields in a database. For example let's take the scenario where you are processing a credit card transaction. ...
Written by Sean Behan on 06/17/2012
Gem Information with Gem List
If you want to get version information about a gem the easiest way to do it is with this command
gem list
For example
gem list activemerchant
will output the activemerchant versions I have installed. You can pass only part of the name like
gem list ...
Written by Sean Behan on 06/17/2012
OpenSSL Certificate Generation Information for Certificate Authority to Serve Traffic Over Https
apt-get install openssl
openssl genrsa -des3 -out server.key 1024
openssl req -new -key server.key -out server.csr
You'll be prompted to enter a password (don't forget it!) as well as fill in company identity information. The most important part is the ...
Written by Sean Behan on 06/17/2012
Install Sphinx on Ubuntu
It's a pretty straightforward process. Download the source and compile it. There isn't a package for it so here are the commands.
wget http://sphinxsearch.com/downloads/sphinx-0.9.8.1.tar.gz
tar xzvf sphinx-0.9.8.1.tar.gz
cd sphinx-0.9.8.1/
./configure...
Written by Sean Behan on 06/17/2012
Chunk an FLV File into Multiple Parts
The format is as follows
ffmpeg -i <input file> -ss <starting point> -t <length of capture> <output file>
ffmpeg -i Input_File.flv -ss 00:00:00 -t 00:10:00 Output_Filename.flv
http://www.surfthedream.com.au/blog/Archives/november...
Written by Sean Behan on 06/17/2012
David Heinemeier Hansson - Ruby on Rails, Startups, Culture
[youtube]http://www.youtube.com/watch?v=sb2xzeWf-PM[/youtube]
Written by Sean Behan on 06/17/2012
Nested Has_one Relationship with Fields_for and Attr_accessible in Model Class
To make child attributes accessible to your model through a nested forms (Rails 2.3) you'll need to add the "#{child_class}_attributes" to the attr_accessible method in your parent class. If you don't use attr_accessible in your parent model (you would do...
Written by Sean Behan on 06/17/2012
Nested Attributes in a Form for Has_One Model Association in Rails
Just for reference...
class Member < ActiveRecord::Base
has_one :member_profile
accepts_nested_attributes_for :member_profile
end
...
Written by Sean Behan on 06/17/2012
Destroy Children In Rails 2.3
In the parent class place the following code
has_many :posts, :dependent => :destroy
This used to be accomplished with
has_many :posts, :dependent=>true
Check out the Rails docs for more information http://api.rubyonrails.org/classes/ActiveRecord/As...
Written by Sean Behan on 06/17/2012
Make Rails Lib Module Methods Available to Views
If you create a module in the lib/ directory of your Rails application you won't have access to those methods in your views. If you don't want to put those methods in a helper file, you need to add a method to your module that makes them available for you...
Written by Sean Behan on 06/17/2012
Use a Cron Job to Automate Sphinx Index Refresh from Rails Rake Task
If using Sphinx, you need to refresh indexes when you add new content to your database. This is fairly easy to do by hand
rake thinking_sphinx:index RAILS_ENV=production
But if you want to automate this and use a cron, remember to set the PATH, SHELL an...
Written by Sean Behan on 06/17/2012
How to Get Your User's SHELL and PATH Information
How to find your user SHELL and PATH on Linux
echo $PATH
echo $SHELL
Which will print the paths to the screen
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
/bin/bash
Written by Sean Behan on 06/17/2012
Installing Feedzirra RSS Parser on Ubuntu 8
I recently watched a RailsCasts episode (http://railscasts.com/episodes/168-feed-parsing) on parsing and persisting RSS feeds using Feedzirra. It took a little setting up on Ubuntu because it relies on some libraries that aren't included with Ubuntu > 8.
...
Written by Sean Behan on 06/17/2012
Email Obfuscation and Extraction from Text with Rails
There is a helper method for handling the obfuscation of email addresses in Rails.
mail_to "me@domain.com", "My email", :encode => "hex"
# => My email
If you want to then extract an email address(or all email addresses) from a block of text here is the...
Written by Sean Behan on 06/17/2012
Fixing MySQL for Rails 2.2 Development on Mac OS X
Oh what trouble Rails 2.2 and MySQL (on Mac OS X) can be. Rails, as of version >= 2.2, no longer comes bundled with the MySQL adapter. This means you'll need to install it yourself, but it appears that the gem for installing it is also broken.
This will ...
Written by Sean Behan on 06/17/2012
Installing Sphinx Search Engine on Mac OS X... or ld: library not found for -lmysqlclient
If you are trying to install Sphinx on Mac OS X, it will most likely fail. The current version of MySQL bundled with Mac OS X is not supported and therefore, it will spit out the error message because it can't find the correct libraries.
ld: library no...
Written by Sean Behan on 06/17/2012
Recursively Zip a Directory and Files on Linux
It's Short and sweet!
Just remember that the finished zip filename is the first argument and the directory you wish to recursively zip comes after.
zip -r name_of_your_directory.zip name_of_your_directory
That's all.
You might be intere...
Written by Sean Behan on 03/05/2017
Why Doesn't Google Offer Dedicated Virtual Hosting?
AppEngine is nice, but it's a little limiting. No cron jobs, filesystem use nor customization with third party libraries, software, databases, languages, etc. You can't deploy PHP, Ruby and or your 'other' favorite web development tools.
You can only use ...
Written by Sean Behan on 06/17/2012
Protect a Directory with Apache, .htaccess and httpasswd
Apache comes with a command line utility called "htpasswd". This utility will generate a username and password that you can use to authenticate against using a .htaccess file. Just run the utility like so:
htpasswd -c /path/to/your/password/directory/a...
Written by Sean Behan on 06/17/2012
Postfix, ActionMailer and OpenSSL Fix on Ubuntu
If you run into problems using ActionMailer > 2.2, Postfix and OpenSSL while sending mail from your application, try changing the following:
vim /etc/postfix/main.cf
Change
smtpd_use_tls=yes
to
smtpd_use_tls=no
OpenSSL support with Postfix does ...
Written by Sean Behan on 06/17/2012
How to Use Pretty URLs with Rails will_paginate Plugin
The will_paginate plugin for Rails uses a key/value assignment like ?page=2, rather than the pretty url formats such as /page/2 ... This is because url generation and mapping are handled by the routes.rb file. You'll need to modify the file so that rails ...
Written by Sean Behan on 06/17/2012
Rails: Expiring a cached page with namespaces and sweepers
I've got some pages that are cached using their permalinks on the filesystem, such as http://example.com/about-us.html which will need to map to RAILS_ROOT/public/about-us.html ... The issue I have is that I use a namespace for the admin area and the cont...
Written by Sean Behan on 06/17/2012
Dot htaccess file for wordpress installation (.htaccess)
Login to your wordpress installation and scroll to and click the second to last link set "Settings". You'll need to configure wordpress to handle your new links as "permalinks". Make a selection and copy the code into your .htaccess file. Wordpress will a...
Written by Sean Behan on 06/17/2012
Custom Date Formats for Your Rails Application
If you use a consistent date format often in your Rails applciation, it is worth it to add the format to your application environment. You can do this by adding it to the bottom of the config/environment.rb file.
Time::DATE_FORMATS[:my_custom_format] ...
Written by Sean Behan on 06/17/2012
Sending eMail with Rails on Mac OS X Development Environment
You'll need a mail transport agent (MTA). I installed and used postfix using Mac Ports.
sudo port install postfix
You'll need to start postfix, to send mail from your Rails application. You can set it as a startup item and it will start on boot. However...
Written by Sean Behan on 06/17/2012
Quick Syntax to Pipe an SQL Query Directly to a file
Here is a quick way to put the contents of a database table into a simple text file. This could be handy if for example, you just want to grab some emails and pop the results into a simple csv file. Your sql statement can be as creative as sql allows. All...
Written by Sean Behan on 06/17/2012
Rails Migrations and Auto Incrementing Migration Prefix Number
In your environment.rb file turn off timestamped migrations like so:
config.active_record.timestamped_migrations = false
Written by Sean Behan on 06/17/2012
How to Install Ferret, the Full Text Search Engine with Your Rails Application
Ferret is a full text search engine based on the popular Lucene Engine, which is originally written for Java. There is a great tutorial available here: http://www.railsenvy.com/2007/2/19/acts-as-ferret-tutorial
Assuming you have the plugin installed, act...
Written by Sean Behan on 06/17/2012
Starting the Rails Console in Production Mode
To specify which mode you'd like the rails console to boot up in, just provide the string without any flags.
./script/console production
./script/console test
./script/console development
If you're on windows, remember the backslash "\" rather than for...
Written by Sean Behan on 06/17/2012
Rails Prototype JS and TinyMCE Autosave
TinyMCE is a nice little WYSIWYG for text processing online. It uses iFrames and Javascript callbacks to manipulate textarea form fields. Using it with Rails can be somewhat problematic if you want to set up an observer on a field that TinyMCE is managing...
Written by Sean Behan on 06/17/2012
Using jQuery and Prototype Javascript Together with jQuery.noConflict();
To use the jQuery javascript framework in a Rails application, that also uses the Prototype framework for the same application, you'll need to reassign the $() function for jQuery to another variable. This is very simple to do. Just make sure to include t...
Written by Sean Behan on 06/17/2012
Set Cron Job to Run Every Five Minutes for a Ruby on Rails Rake Task
First off you'll need to edit your cron file. Normally, the cron files are kept under /etc/cron.daily or /etc/cron.hourly but we can just use the command line tool, crontab and pass it the -e flag, so that we can edit the file without any fuss.
sudo cron...
Written by Sean Behan on 06/17/2012
Validate Uniqueness on Join Tables in Rails
How to validate uniqueness in a :has_many :through relationship with Ruby on Rails. You'll need three models in this example List, Subscriber and ListSubscriber. A list has many subscribers and a subscriber has many lists. Simple enough. Running the follo...
Written by Sean Behan on 06/17/2012
YouTube Internal Server Error
Thought I'd share a snapshot of this error message from youtube.com. It's nice to know that their monkeys are highly trained. I figured they just got those lazy monkeys who work for bananas.
500 Internal Server Error
Sorry, something went wrong.
A team o...
Written by Sean Behan on 06/17/2012
When the cloud is a good idea
A buddy of mine is a talented, but paranoid System Administrator for a small web company. He refuses to see the truth and the beauty in the wonderful world made possible by cloud computing services like Amazon's EC2. Amazon is not the only game in town. T...
Written by Sean Behan on 06/17/2012
Wildcard VirtualHost with Apache2
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.co...
Written by Sean Behan on 06/17/2012
Ruby strftime() method arguments
Just for reference strftime() arguments in ruby.
Usage `Time.now.strftime("%B/%d/%Y")`
%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,...
Written by Sean Behan on 03/05/2017
Namespacing in 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 t...
Written by Sean Behan on 06/17/2012
Using Prototype to Access Form Data
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 update...
Written by Sean Behan on 06/17/2012
Parse for Links with Prototype JS
Parsing for links with the Prototype javascript library is easy. Here is the pattern for finding links
/(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^
=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/
And to implement it you can loop through your con...
Written by Sean Behan on 06/17/2012
Add Users to a Group on Ubuntu
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 accou...
Written by Sean Behan on 03/02/2017
paypal ipn simulator
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 transactio...
Written by Sean Behan on 06/17/2012
git checkout -- file-in-question.oh-my
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 sch...
Written by Sean Behan on 06/17/2012
rails fixtures: using the right timestamp
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_R...
Written by Sean Behan on 06/17/2012
the simple things with git
Git can track the file permissions on your source. This can be good, but for small projects on a webserver where permissions change from time to time, and permissions on development app don't match or matter anyway, it's often easier to just skip this che...
Written by Sean Behan on 06/17/2012
upgrading to latest phusion passenger 2.1.2
super easy
gem install passenger
passenger-install-apache2-module
will walk you through the install and remember to copy paths to your apache config file. for passenger i kept it in
mods-available/passenger.conf and then linked it to mods-enabled
ln -s...
Written by Sean Behan on 06/17/2012
mysql on rails 2.3.2
mysql driver is no longer bundled w/ rails. you'll need to install it yourself w/
sudo gem install mysql
however, on ubuntu (heron) this won't work. issue these commands first
sudo apt-get install libmysql-ruby libmysqlclient-dev
if libmysqlclient-dev...
Written by Sean Behan on 06/17/2012
Rails, SSL, Ubuntu, Apache2 with Phusion on Ubuntu
Here are all the commands for setting up your Rails application to server requests over SSL -on Ubuntu, of course.
There are great resources and tutorials at these websites.
http://www.tc.umn.edu/~brams006/selfsign.html
http://www.tc.umn.edu/~brams006/se...
Written by Sean Behan on 06/17/2012
Setting up a new ubuntu server with apache2, php, ruby on rails, rubygems, mysql, and git
Here are a list of commands to get up and running with Apache2 with Phussion Passenger for Rails, PHP5, MySQL5, Ruby on Rails with Gems, and the source control software Git. I think that this is a pretty ideal environment for a development box and even pr...
Written by Sean Behan on 06/17/2012