Ruby

Favorite Ruby Feeds

Ruby

Over a year ago, I write a post about my favorite Ruby feeds. I’ve since deleted that post in order to write about an updated set of Ruby feeds that you should be paying attention to (if not already). I read all of these feeds religiously on a daily basis and have broken them down below by general news and information followed by screencasts/tutorials. Enjoy.

News

  • A Fresh Cup - My personal favorite. While you can find similar news via the links below, Mike Gunderloy does an excellent job of summing everything up in place for news, information, and new gems from the Ruby community.
  • Ruby Toolbox - A great trending site for finding out what gems are hot and most popular within the Ruby community. This can save you a lot of time when you want to know which gem is the best solution for a problem that has already been solved.
  • Ruby Trends - Another trending site. Useful for cross-checking against Ruby Toolbox on what is hot.
  • Ruby News - Straight from the source. Find about new releases, conferences, developments, etc.
  • Ruby Inside - The inside scoop on Ruby news.
  • RubyFlow - A great site for picking up new resources to add to your development repertoire.
  • RubyFu - Useful quick news and resource links.
  • Ruby Best Practices - A great source of thoughtful discussion, including code samples, on how to write better code.
  • Ruby5 - From some of the same guys who provide the Rails Envy podcast below. This is another podcast on Ruby news but in short, 5-minute, segments of usually discussing many of the new and interesting gems being developed.
  • Rails Inside - Get the inside scoop on Rails news.
  • Riding Rails - Learn what is happening with the Ruby on Rails team.
  • Rails Spikes - A multi-authored site of Ruby developers discussing news, tips, code, etc.
  • Rails Illustrated - Info on Rails, web design, and the user experience.
  • Rails Notes - Another site worth checking out and picking up new learning.
  • Rails Tips - As the site description goes: “One man, feverishly posting everything he learns.”
  • The Rails Way - News and information dedicated to teaching best practices of Ruby on Rails.
  • Ruby on Rails Security Project - A good place to read up on security issues or at least keep your mind in it.
  • Giant Robots Smashing Into Other Giant Robots - Good development tips and tricks, mostly related to Rails.
  • Ryan’s Scraps - Interesting news on what’s new and upcoming within the Rails code base. Includes code samples and detailed descriptions and examples of new Rails features.
  • Has Many Through - Although he has a low writing frequency, the posts are enlightening.
  • Rails Envy - An entertaining and informative weekly podcast dedicated to Ruby, Rails, and web framework news.
  • Rails Podcasts - Ruby/Rails podcasts by Geoffrey Grosenbach of PeepCode fame.
  • Rails Magazine - News, articles, and information about the Ruby on Rails framework.

Tutorials

  • Railscasts - Short screen cast tutorials of Ruby on Rails code.
  • Envy Casts - Produced by the same guys that host the Rails Envy podcasts. Each screen cast tutorial will set you back about $9.
  • PeepCode - Screencast tutorials like Railscasts but longer in length and not free (roughly $9 per episode).
  • Tekniqal - A collection of screencasts that cover some of the Ruby basics.
  • Scaling Rails - A series of screencasts on detailing how to scale your Ruby on Rails application appropriately. Produced by Gregg Pollack of Envy Cast fame.
  • BDD Casts - Video tutorials on all things related to Behavior Driven Development.

BTW, you can find this list and more on my Ruby page.

Tags: ,

Tuesday, October 6th, 2009 Software No Comments

MacOS Ruby Development Setup

Ruby

For those wanting to set up a proper Ruby and Ruby on Rails development environment for your MacOS, I’ve created an OmniOutliner outline that I use. Its my personal guide to getting my development environment setup properly especially if one has erased and install the operating system from scratch.

When making the outline, I pulled heavily from the following articles (also found on my MacOS page) with a few modification here and there:

You can download the outline for your own use here:

In the future, I hope to provide this outline in both original and HTML format but for now, I just have the OmniOutliner format. Apologies to those who don’t use OmniOutliner.

Tags: ,

Monday, September 28th, 2009 Software No Comments

jQuery on Rails Talk

Not Just Ruby (NJR)

For those in the Colorado Springs area, I’ll be giving a talk tomorrow at Panera Bread for the Not Just Ruby (NJR) group on the merits of jQuery as your JavaScript framework of choice when building Ruby on Rails apps. The talk is both an intro to jQuery (in some sense) as well as how to make jQuery easy to use after I have weened you off of the out-of-the-box Rails helpers. You’ll learn to write unobtrusive JavaScript code, support graceful degradation, not open yourself up to security holes, and more.

For those of you who would like to get a jumpstart on the talk, here are the files I’ll be using for the talk:

In the strange event that you are not able to install the necessary gems needed to run the Ruby on Rails demo provided above, then you can goof around with the live version here if you like. I know the demo doesn’t look like much but its what is happening under the covers that will be of interest.

See you at the meeting tomorrow!

Tags: , ,

Tuesday, September 1st, 2009 Meetups No Comments

Quickly Filtering Ruby Methods

Ruby on Rails

Sometimes, when working with IRB or the Rails console, you might need a list of methods on a particular class or object. You don’t necessarily need to consult the doc because it is one of those situations where you would know the method if you saw it. So what do you do? Well, one trick is to use the select method (passed via a block) on a collection of methods. You can always start by asking the class for its methods by typing the following:

Hash.methods

Which yields:

["require_dependency", "decode_b", "write_inheritable_hash", "model_name", "breakpoint", "require", "delegate", "taguri", "const_missing", "new", "class_inheritable_hash", "suppress", "methods", "andand", "method", "allocate", "attr_internal_reader", "protected_instance_methods", "deprecate", "taguri=", "subclasses", "cattr_accessor", "include?", "daemonize", "taint", "present?", "class_eval", "alias_method_chain", "instance_variable_defined?", "yaml_tag_class_name", "name", "find_hidden_method", "reset_inheritable_attributes", "metaclass", "autoload", "to_yaml_style", "class_variables", "parent", "inheritable_attributes", "__id__", "singleton_methods", "synchronize", "dclone", "private_instance_methods", "object_id", "subclasses_of", "respond_to?", "nil?", "ancestors", "yaml_tag_read_class", "parent_name", "tap", "__send__", "require_library_or_gem", "protected_methods", "require_or_load", "me", "tainted?", "attr_internal_writer", "remove_class", "class_inheritable_reader", "untaint", "instance_of?", "autoload?", "b64encode", "included_in_classes", "equal?", "method_defined?", "with_options", "const_missing_without_dependencies", "display", "class_variable_defined?", "private_methods", "hash", "instance_method", "send", "constants", "deprecation_horizon", "instance_values", "`", "attr_internal_accessor", "yaml_tag_subclasses?", "class_inheritable_writer", "kind_of?", "enable_warnings", "freeze", "eql?", "public_method_defined?", "to_json", "id", "returning", "parents", "write_inheritable_attribute", "dont", "acts_like?", "require_association", "public_methods", "instance_eval", "superclass_delegating_reader", "instance_variable_names", "attr_internal", "const_get", "to_enum", "class_inheritable_array_writer", "is_a?", "silence_stderr", "private_method_defined?", "cattr_reader", "type", "const_missing_with_dependencies", "local_constants", "superclass", "write_inheritable_array", "instance_variables", "frozen?", "blank?", "attr_internal_naming_format", "const_set", "copy_instance_variables_from", "enum_for", "class_inheritable_hash_writer", "silence_stream", "to_a", "to_param", "mattr_reader", "protected_method_defined?", "attr_internal_naming_format=", "extended_by", "silence_warnings", "class", "public_class_method", "encode64", "from_xml", "instance_variable_get", "<=>", "to_yaml", "load_with_new_constant_marking", "==", "superclass_delegating_writer", "method_added", "class_inheritable_accessor", "===", "duplicable?", "extend", "to_s", "to_query", "alias_attribute", "instance_methods", ">=", "remove_subclasses", "extend_with_included_modules_from", "mattr_writer", "<=", "cattr_writer", "local_constant_names", "clone", "private_class_method", "decode64", "read_inheritable_attribute", "const_defined?", "yaml_as", "included_modules", "debugger", "=~", "instance_variable_set", "<", "superclass_delegating_accessor", "deprecated_method_warning", "attr_accessor_with_default", ">", "class_inheritable_array", "inspect", "[]“, “remove_subclasses_of”, “instance_exec”, “try”, “mattr_accessor”, “public_instance_methods”, “as_load_path”, “to_yaml_properties”, “unloadable”, “dup”, “module_eval”]

OK, yeah, that’s a bit overkill. How about we narrow it down to the types of methods (using the select method with a regular expression):

Hash.methods {|m| m.select =~ /methods/}

Which yields:

["methods", "protected_instance_methods", "singleton_methods", "private_instance_methods", "protected_methods", "private_methods", "public_methods", "instance_methods", "public_instance_methods"]

Ah, much better. …but I’m not quite there yet. Lets say I know it’s an instance method and it is a type of “to” method. I could then type the following:

Hash.instance_methods {|m| m.select =~ /to_/}

Which yields:

["to_yaml_style", "to_hash", "to_set", "to_xml", "to_json", "to_enum", "to_options", "to_a", "to_param", "to_yaml", "to_options!", "to_s", "to_query", "to_yaml_properties"]

OK, now I remember, it was the “to_yaml” method that I was looking for!

This, of course, is a contrived example. However, if you know what type of method you are looking for and part of its name, then this is a quick and effective way of getting back a subset of methods from which you can gauge what it is that you’re looking for.

Where I tend use this most (as of late) is with Rails models that accept nested attributes (i.e. accepts_nested_attributes_for). For example:

Recipe.instance_methods {|m| m.select =~ /attributes/}

["update_attributes!", "comments_attributes=", "reject_new_nested_attributes_procs", "attributes", "attributes=", "time_zone_aware_attributes", "respond_to_without_attributes?", "update_attributes", "skip_time_zone_conversion_for_attributes", "user_recipe_attributes=", "ingredient_groups_attributes=", "attributes_before_type_cast", "instructions_attributes=", "sources_attributes="]

So there you have it, in case it is of help.

Tags: ,

Tuesday, June 16th, 2009 Software No Comments

Ruby on Rails Quick Start

Rails

Introduction

Ruby on Rails is a web framework built on top of the Ruby programming language that focuses on convention over configuration to get things done. It was originally developed by David Heinemeier Hansson at 37signals for the Basecamp application. Eventually, the framework was extracted from Basecamp, open sourced, and is now known as Ruby on Rails. It is also a total pleasure to work with.

Requirements

It is assumed that you have knowledge of the Ruby language and a working development environment in order to make use of this post. Read my Intro to Ruby article series if you need further instruction.

Literature

  1. Build Your Own Ruby on Rails Web Applications by Patrick Lenz - This was the first book that I read on the Rails framework that walks you through building a simple web application from start to finish. Something to consider but you might enjoy the book listed below better.
  2. Agile Web Development with Rails, Third Edition - Have not read this book myself as of yet but have heard very good things about it.
  3. RESTful Rails - A free PDF available for download. While knowing the REST architecture is not a prerequisite to developing Ruby on Rails applications, I would strongly recommend that you take time to understand how to use it. You’ll be glad you did.

API

Good bookmarks to have on hand are:

  • API Doc - Provides quick keyword search capabilities as well as community comments for Ruby and Ruby on Rails. My personal favorite.
  • Got API - An alternative to API Doc but not as easy on the eyes. Depends on your temperament, of course.

News

The following feeds are worth adding to your feed reader in order to stay connected with the community:

Tools

Using a simple text editor like TextEdit (MacOS) or Notepad (Windows) will do just fine for starters. However, you might consider the following tools as better alternatives to simple text editors:

  • TextMate - Lightweight, fast, and costs $30. For the MacOS platform only.
  • NetBeans - Developed by Sun and free to use. Works on multiple platforms.
  • Aptana - Adds Ruby on Rails support to the Eclipse IDE. Visit the software update site to install directly into Eclipse.

I am a MacOS guy, so TextMate is my development tool of choice when writing Ruby code. However, if you are not on the MacOS I would recommend Netbeans as it is less buggy than Eclipse (although I do like the Eclipse UI better).

In addition to the tools mentioned above, you might consider installing the SQLite Manager Firefox add-on for quick and easy access to your SQLite3 database. You can find this and other recommended plugins for Firefox on my Firefox page.

Installation

Installation and setup is as simple as installing a few Ruby gems. Execute the following commands from a command line in the following order:

  1. sudo gem install rails
  2. sudo gem install mongrel
  3. sudo gem install sqlite3-ruby

When you generate a rails app it will default to using the SQLite3 database. Feel free to install MySQL or some other database for your development needs. The Mongrel gem installs a web server stack for running your Rails application. By default, you can run Rails on WEBrick but I recommend using Mongrel instead.

Creating a Rails App

To create your first Rails app, open a terminal window in a working directory of your choice. Then execute the following command:

rails MySpiffyApp

This will create a new folder in your working directory called “MySpiffyApp”. Inside this directory you will have set of files and folders that represent the default Rails web application structure. Make sure to read the README file located in the root of “MySpiffyApp” directory to make sense of the file and folder structure.

Running Your Rails App

Right, so now you have a Rails app but how do you run it? While still in your terminal window, change to the root of your Example project folder and type:

script/server -u

This will launch your Rails app with debugger support enabled (i.e. the “-u” option). To view your app, just plug this address in your web browser: http://localhost:3000

Congratulations, you have successfully installed Rails, built a Rails app, and seen it running!

Next Steps

I will be releasing various bits of code in the future that will make building your Ruby on Rails apps easier. Stay tuned if you want to learn more and don’t be afraid to send me some feedback as comments are always welcome.

Tags:

Monday, March 9th, 2009 Software No Comments

Intro to Ruby - Next Steps

Ruby

Conclusion

This concludes the article series on the Ruby language. If you have feedback, questions, etc. just leave comments on the various topics in question. Otherwise, feel free to contact me directly.

As for your next steps, I would suggest subscribing to as many Ruby syndicated feeds that you can handle. It is the best way to learn something new and stay connected to the vibrate Ruby community. Finally, you can always use my Ruby page as a launch point for your own purposes.

Where to find Me

You can find me at the following locations:

  • Berserk Technologies - My Ruby consulting business. If you are in need of a Ruby developer with industry experience and who truly loves what he does then don’t hesitate to contact me.
  • Twitter - I’m always jabbering about Ruby and technology in general so if you find this site too long in the tooth then you might enjoy shorter versions of what I write…or not. Hey, all of this is syndicated so the choice is always yours whether you want to tune in or not.
  • Not Just Ruby - Join Kevin and I for spirited discussions related to Ruby, business, design, marketing, etc. The group is growing and we are always looking for more people who are enjoy thinking outside of the box so-to-speak.
  • Colorado Springs Entrepreneurs Group - Be a part of a group that allows entrepreneurial spirits to soar. Remember, you are always an Enterprise of One whether you acknowledge it or not.
  • Colorado Springs Open Source Software Group - Dedicated to all things open source. You can find me in speaking or just hanging out in the audience.

What’s Next

I’ll be focusing on releasing some open source software shortly that will make building Ruby on Rails apps easier. I’ll also be talking about Ruby on Rails more in general.

See you space cowboy.

Tags:

Sunday, March 8th, 2009 Software No Comments

Intro to Ruby - Testing

Ruby

Overview

The following is a demonstration of testing in Ruby using the Test::Unit framework that is provided with Ruby by default. Other testing frameworks worth considering are:

  • RSpec - My testing framework of choice at the moment. Focuses on behavior driven design (BDD).
  • Shoulda - Another testing framework that integrates nicely with Test::Unit and even plays well with RSpec in some cases.

Test::Unit will be more familiar to those from the Java space due to the assert methods. A good gem to use for automation of your testing is the ZenTest (a.k.a. autotest) gem.

Code


# Requirements for Test::Unit
require "test/unit"

# A simple class to be used for testing.
class Simple
  def self.who_am_i
    "I am #{name.downcase}"
  end

  def add a, b
    a + b if a && b
  end

  def multiply a, b
    a * b if a && b
  end

  def echo string = "Echo"
    string
  end
end

# The test class that captures the various tests to be run against the Simple class.
class SimpleTest < Test::Unit::TestCase
  def setup
    @simple = Simple.new
  end

  def test_good_add
    assert @simple.add(1, 1), 2
  end

  def test_bad_add
    assert_nil @simple.add(nil, nil)
  end

  def test_who_am_i
    assert_kind_of String, Simple.who_am_i
  end
end

Output

Started
...
Finished in 0.000347 seconds.

3 tests, 3 assertions, 0 failures, 0 errors

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 14-testing.rb.

What’s Next

Tags:

Sunday, March 8th, 2009 Software No Comments

Intro to Ruby - Exceptions

Ruby

Overview

The following demonstrates exception handling and creation of custom exceptions within the Ruby language. Study the code below and be sure to read the comments for each example to understand what is going on. BTW, while not shown below, you don’t have to use the begin keyword when dealing with exceptions. Something to keep in mind.

Code


# The following raises and rescues an exception.
puts "01 Exception Rescued\n\n"
begin
  raise
rescue
  puts "Hmm, something happened."
end

# The following raises an exception with a message and then rescues it.
# This time we use the global variable '!', which is a convenient reference to the
# exception, to list details about the exception.
puts "\n02 Exception (with a message) Rescued\n\n"
begin
  raise "Ouch!"
rescue
  puts $!.message
  puts $!.inspect
end

# Example of a valid exception where a method on an object does not exist.
puts "\n03 No Method Exception\n\n"
begin
  ruby = "Ruby"
  ruby.this_is_not_a_method
rescue
  puts "Opps, unknown method."
  puts $!.inspect
end

# Example of a clean run with no errors.  Use of the esle and ensure statements are shown as well.
puts "\n04 A Clean Run\n\n"
begin
  puts "Begin."
rescue
  puts "Opps, something happened."
else
  puts "Else."
ensure
  puts "Ensure."
end

# The following demonstrations creating and using a custom exception.
puts "\n05 A Custom Exception\n\n"
class ExampleError < RuntimeError
  attr_reader :message

  def initialize message
    @message = message
  end
end

begin
  raise ExampleError.new("King for a Day, Fool for a Lifetime")
rescue
  puts $!.message
  puts $!.inspect
end

# The following is a simple example of a catch/throw to deal with exceptions.
puts "\n05 Catch and Throw\n\n"
catch :example do
  puts "I made it here..."
  throw :example
  puts "...but not here."
end

Output

01 Exception Rescued

Hmm, something happened.

02 Exception (with a message) Rescued

Ouch!
#<RuntimeError: Ouch!>

03 No Method Exception

Opps, unknown method.
#<NoMethodError: undefined method `this_is_not_a_method' for "Ruby":String>

04 A Clean Run

Begin.
Else.
Ensure.

05 A Custom Exception

King for a Day, Fool for a Lifetime
#<ExampleError: ExampleError>

05 Catch and Throw

I made it here...

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 13-exceptions.rb.

What’s Next

Testing

Tags:

Friday, March 6th, 2009 Software 2 Comments

Intro to Ruby - Loops

Ruby

Overview

The following is a look at Ruby loops such as while, until, and loop. These should be familiar to you from other languages but make sure to take a look at the map, inject (a.k.a. reduce), and select methods. These are powerful looping constructs that will allow you to accomplish a lot in only a single line of code. To learn more about these loops, take some time to read “functional programming and looping and Understanding map and reduce as originally discussed on the Rails Spikes site.

Code


class Loopy
  COLORS = ["red", "blue", "green", "white", "yellow"]

  def print_time_1
    future = Time.now + 5
    while Time.now < future do
      puts Time.now
      sleep 2
    end
  end

  def print_time_2
    future = Time.now + 5
    until Time.now > future do
      puts Time.now
      sleep 2
    end
  end
end

loopy = Loopy.new

# A "for each" loop that prints each color in an array.
puts "01 For Each\n\n"
Loopy::COLORS.each {|color| puts color}

# A "for in" loop that performs the same logic as the "for each" loop above.
puts "\n02 For In\n\n"
for color in Loopy::COLORS do
  puts color
end

# An example of a while loop that prints time while a condition is not met.
puts "\n03 While\n\n"
loopy.print_time_1

# An example of until loop that prints time until a condition is met.
puts "\n04 Until\n\n"
loopy.print_time_2

# An example of a "loop" loop.  Again using time to break out, otherwise the loop will run indefinitely.
puts "\n05 Loop\n\n"
time = Time.now + 1
count = 0
loop do
  puts "Hey, I'm inside the loop" if count == 0
  count += 1
  break if Time.now > time
end
puts "Exited loop, total count: #{count}"

# An example of the a mapping loop that generates a new array of colors that are all uppercase.
puts "\n06 Map\n\n"
puts Loopy::COLORS.map {|color| color.upcase}

# The following reduces a range of numbers to a single value.
puts "\n07 Reduce\n\n"
puts (1..5).inject(0) {|sum, value| sum + value}

# The following returns a new array of colors but only those that have the letter 'l' in them.
puts "\n08 Select\n\n"
puts Loopy::COLORS.select {|color| color['l'] }

Output

01 For Each

red
blue
green
white
yellow

02 For In

red
blue
green
white
yellow

03 While

Sun Mar 01 10:29:05 -0700 2009
Sun Mar 01 10:29:07 -0700 2009
Sun Mar 01 10:29:09 -0700 2009

04 Until

Sun Mar 01 10:29:11 -0700 2009
Sun Mar 01 10:29:13 -0700 2009
Sun Mar 01 10:29:15 -0700 2009

05 Loop

Hey, I'm inside the loop
Exited loop, total count: 719438

06 Map

RED
BLUE
GREEN
WHITE
YELLOW

07 Reduce

15

08 Select

blue
yellow

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 12-loops.rb.

What’s Next

Exceptions

Tags:

Thursday, March 5th, 2009 Software No Comments

Intro to Ruby - Conditionals

Ruby

Overview

The following is a brief example of conditional logic in the Ruby language. Most of this should be familiar to you from other languages but convenience syntax like “unless” (opposite of “if”) might be new to you. As a rule of thumb, try not to use an “unless” with an “else” expression even though it would be syntactically correct. This is generally frowned upon and one should use the “if”, “else” expressions instead (much easier to read). Go ahead, study and play with the code yourself.

Code


class MerDeNoms
  NAMES = ["Billy", "Charlie", "Merideth", "Dirk", "Sandra"]

  def print_names
    NAMES.each {|name| puts name}
  end

  def has_name? name
    puts NAMES.include?(name) ? "#{name} is found." : "#{name} is not found."
  end

  def print_speciality name
    puts "#{name} is not special." unless NAMES.include?(name)
  end

  def print_bio name
    date = ""
    if name == "Billy" then date = "1970"
    elsif name == "Charlie" then date = "1950"
    elsif name == "Merideth" then date = "1977"
    elsif name == "Dirk" then date = "1990"
    elsif name == "Sandra" then date = "2000"
    else date = "?"
    end
    puts "#{name} was born in #{date}."
  end

  def print_status name
    description = ""
    case name
    when "Billy" then description = "is sleeping."
    when "Sandra" then description = "is hungry."
    else description = "is day dreaming."
    end
    puts "#{name} #{description}"
  end
end

names = MerDeNoms.new

# An example of the ternary operator.
puts "01 Ternary\n\n"
names.has_name? "Fred"

# An example of the "unless" statement.  NOTE: You could also use the "if" statement in this manner as well.
puts "\n02 Unless\n\n"
names.print_speciality "Fred"

# An example of elsif logic.
puts "\n03 ElseIf \n\n"
names.print_bio "Dirk"

# An example of the case statement.
puts "\n04 Case \n\n"
names.print_status "Dirk"

Output

01 Ternary

Fred is not found.

02 Unless

Fred is not special.

03 ElseIf

Dirk was born in 1990.

04 Case

Dirk is day dreaming.

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 11-conditionals.rb.

What’s Next

Loops

Tags:

Wednesday, March 4th, 2009 Software No Comments