VocabReminder
Easily build a great vocabulary without studying! Now on the App Store!
Click here for more info about the app

Posts Tagged with "Ruby"

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 mont...


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 no...


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,...


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...


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 secon...


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 succes...


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 < ActionControlle...


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 fi...


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...


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...


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)...


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 Proc...


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 si...


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...


How To Create Blurry Background Images Programmatically from the Command Line or with Ruby

Turn this into this <img src='http://f.cl.ly/items/...


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 friend...


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...


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.seanbe...


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 instal...


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 rep...


How To Add A Route With A Forward Slash in Params with Rails 3 Application

Use an asterisk in the pattern to match for everything after it. In the example below, date will be available in the params hash as params[:date]....


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...


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.upc...


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 immediate...


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 Appro...


Class

# Define a class with a class method "find" # Usage # Apple.find("macintosh") class Apple def self.find(variety) # code goes here e...


Email Regex

Regular Expression that Matches Email Addresses: /\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b/...


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 </pre...


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...


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 a...


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...


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...


My First Ruby Gem: Hashed_Attributes

I just wrote and released my first Ruby Gem, Hashed Attributes https://rubygems.org/gems/hashed_...


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 yo...


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 st...


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...


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....


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 :publis...


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....


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...


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 ex...


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 bein...


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 <...


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 versio...


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...


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 D...


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 serve...


Using to_sentence method on an Array in Ruby on Rails

Member.all.collect {|member| member.firstname}.to_sentence => "Alex, Andy, and Sean" Declare separator and the connector Member....


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 num...


Repost

This post is inspired by http://pupeno.com/blog/really-resetting-the-database/#commen...


Select Distinct in Rails with Active Record

User.find :all, :select => "DISTINCT occupation"...


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 mome...


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 don...


Using Formtastic to Cleanly Create Nice Looking Forms in Rails

Forms can easily get cluttered when you're dealing with a lot of form fields... er, ERB tags. I've written about <a href="http://seanbehan.com/ruby-on...


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 r...


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 direct...


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...


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 <%= render :partial...


Postlearn Job Board

Postlearn is a job board focused on delivering quality jobs listings to people in education.<!--more...


Workshop Dog

Workshop Dog is a free events calendar for dog training workshops and group lessons....


Natural Dog Training Buzz

NDT Buzz is a companion news site to Natural Dog Training. News and info...


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...


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 con...


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 ab...


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 instanc...


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)...


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 thi...


Active Record Find Methods

Active Record find methods for selecting range from http://charlesmaxwood.com...


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...


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 fu...


Rails Plugin Acts as Taggable on Steriods

You can download it here http://github.com/suitmymind/acts-as-taggable-on-steroids...


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 littl...


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 Developmen...


Ruby Strftime Day Without the Leading Zero

%e # rather than %d Time.now.strftime("%e")...


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...


Hello Rack

What is Rack? Rack provides a minimal, modular and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests...


Placing an Authenticity Token in a Rails Form

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>...


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...


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... File...


How to Install a Ruby Package without Ri or RDoc

gem install --no-rdoc --no-ri rails...


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 Arr...


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...


A Through Z

How to print the alphabet in Rails very easily. ("A".."Z").each {|letter| link_to letter, "/#{letter"} "A".upto("Z") {|letter| lin...


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 ea...


link_to_function Rails Ajax Reference

Link_to_function syntax for Haml template. Notice the "|" pipe which will allow for new lines in your code. = link_to_function( "Add Line Item")...


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 pret...


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...


Date and Time Helpers in Rails

Just for reference http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#M001695 This post was created about <%= time_ago_in_wo...


Cool Conditional Syntax in Ruby (on Rails)

Ruby is beautiful @posts = if true Post.all else [] end Simply elegant!...


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 ./s...


Install MySQLdb for Python on Mac OS X

I don't do much python development. I really like the language and there are a lot of great software projects out there for it. Tornado, for example,...


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:d...


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' P...


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-...


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...


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...


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, fo...


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 field...


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 ge...


David Heinemeier Hansson - Ruby on Rails, Startups, Culture

[youtube]http://www.youtube.com/watch?v=sb2xzeWf-PM[/youtube]...


Ruby on Rails vs. PHP in a Nutshell

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


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_ac...


Nested Attributes in a Form for Has_One Model Association in Rails

Just for reference... class Member...


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 :p...


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...


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:i...


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...


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" # => <...


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, languag...


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: v...


Install Rmagick on Ubuntu with MagickWand

apt-get install librmagick-ruby1.8 apt-get install libmagickwand-dev gem install rmagick The last command will spit out a bunch of...


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 ur...


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...


Using Your Partials in Your Liquid Templates

I'm working on a project that requires users/designers be allowed to edit the layout of their site. I'm using Liquid, Ruby templating system developed...


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...


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...


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...


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 ./scri...


Sample Rails Database Config for MySQL

Sample Ruby on Rails database config file for connecting to mysql. production: adapter: mysql encoding: utf8 reconnect: false database:...


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 wit...


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 comm...


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 List...


named_scope in Rails

Take advantage of the named_scope method in your models and make find queries simple and beautiful! #app/models/comment.rb class Comment < Acti...


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 yo...


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 agai...


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 ap...


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...


using rails paperclip plugin on ubuntu

paperclip is an awesome plugin for rails. it let's you attach an image to any of your models. installation and usage more information is available at...


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 tuto...


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 sourc...