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 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 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 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 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 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
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
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 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
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 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
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
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
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
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
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 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
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
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
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
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 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 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
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
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
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
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
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
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
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
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
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
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
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
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
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
Select Distinct in Rails with Active Record
User.find :all, :select => "DISTINCT occupation"
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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\-\.,@?^ =%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/ And to implement it you can loop through your con...
Written by Sean Behan on 06/17/2012