Ruby Weekly is a weekly newsletter covering the latest Ruby and Rails news.

Author Archives: Peter Cooper

By Peter Cooper / May 30, 2006

NArray is an Numerical N-dimensional Array class. Supported element types are 1/2/4-byte Integer, single/double-precision Real/Complex, and Ruby Object. This extension library incorporates fast calculation and easy manipulation of large numerical arrays into the Ruby language.

It’s impressive stuff, if you can understand the math. NArray lets you create arrays with any number of dimensions, and gives you methods that let you perform complex matrix math. There are some great demonstrations, including image resizing and image smoothing with the class. Or how about the Game of Life in under 40 lines of code? Read More

By Peter Cooper / May 29, 2006

Kevin Clark looked at his options for testing his RJS (Javascript templates for Rails) templates but wasn’t happy with the limited options, so he rolled his own testing system as a Rails plugin. It’s called ARTS (Another RJS Testing System) and is available here. It’s pretty neat, and if your app uses a lot of RJS templates, you’re going to want it. Here’s an example of a test using ARTS:

def test_create_rjs
xhr :post, :create, :post => {:title => “Yet Another Post”, :body => “This is yet another post”}
assert_rjs :insert_html, :bottom, ‘posts’
assert_rjs :visual_effect, :highlight, “post_#{assigns(:post).id}”
end

Here are some general examples of how powerful it is:

assert_rjs :alert, ‘Hi!’
assert_rjs :assign, ‘a’, ’2′
assert_rjs :call, ‘foo’, ‘bar’, ‘baz’
assert_rjs :draggable, ‘draggable_item’
assert_rjs :drop_receiving, ‘receiving_item’
assert_rjs :hide, “post_1″, “post_2″, “post_3″
assert_rjs :insert_html, :bottom, ‘posts’, “Here’s text from insert_html”
assert_rjs :redirect_to, :action => ‘list’
assert_rjs :remove, “post_1″, “post_2″, “post_3″
assert_rjs :replace, :bottom, ‘This is something to replace’
assert_rjs :replace_html, “This is something for replace_html”
assert_rjs :show, “post_1″, “post_2″, “post_3″
assert_rjs :sortable, ‘sortable_item’
assert_rjs :toggle, “post_1″, “post_2″, “post_3″
assert_rjs :visual_effect, :highlight, “posts”, :duration => ’1.0′

Technorati Tags: ,

Read More

By Peter Cooper / May 29, 2006

Tobias Lütke needed to migrate a database from one architecture to another but needed to copy the data across intact. To ensure that the format would be architecture agnostic, he’s created a plugin that dumps the data to YAML and then reloads it back into the database at the other end. It’s a simple rake task, and Tobi gives quick and easy instructions.

Technorati Tags:

Read More

By Peter Cooper / May 28, 2006

People who are considering Rails as a platform often ask what it’s integration with tools like HTTP authentication are like, often because that’s the way they’re currently solving certain problems. Up till now HTTP authentication has been something you’ve had to implement yourself, but now there’s a plugin. Install it like so:

ruby script/plugin install http://wota.jp/svn/rails/plugins/branches/stable/htpasswd

And use code like this in your controllers:

class AdminController < ApplicationController
htpasswd :user=>"maiha", :pass=>"berryz"
htpasswd :user=>"maiha", :pass=>"7Et1Y7tCawx32", :type=>:crypted
htpasswd :user=>"maiha", :pass=>"berryz", :realm=>"Member Only"
htpasswd :file=>"/usr/local/apache/passwd/.htpasswd"
end

Neat, huh? Learn more in this interesting blog post about the plugin. Congratulations to maiha for such a useful plugin. Read More

By Peter Cooper / May 28, 2006

Rodney, the Pin Up Geek, has set out to demystify the routing system in Ruby on Rails. He provides lots of basic code examples and shows you how to use most of the features of routes, like in this example of a requirements based route that only routes when a postal code is included in the URL:

map.geocode ‘geocode/:postalcode’, :controller => ‘geocode’,
:action => ‘show’,
:postalcode => /\d{5}(-\d{4})?/

Excellent article for beginners and gurus alike (there’s always something new to learn). Read More

By Peter Cooper / May 28, 2006

Simon Harris laments:

As much as I love Ruby on Rails, one of the things that dissapoints me is the rather large number of static methods. Maybe it’s my Java background but class methods just irk me: They’re difficult to override, mock, stub-out, and they’re inherintly thread-unfriendly. But that aside, the fact remains that they exist and, now and again, I need to mess with them.

He proceeds to look at chaining methods with alias_method. This is an area where there’s MTOWTDI (More Than One Way To Do It) and his examples are worth checking out. Read More

By Peter Cooper / May 27, 2006

Jeremy Voorhis has written an interesting, and seemingly overlooked, article about asset management in Ruby and Rails. Firstly he talks about using rake to build a basic asset compiler, and then demonstrates a basic DSL (Domain Specific Language) he created to manipulate image assets in only a few lines of code. An example: Read More

define_image_transformation ‘thumbnailize’ do
crop_to ’62×62′, :north
end

define_image_transformation ‘bronze’ do
greyscale
lighten
# r g b tint
tint 0.25, 0.25, 0.25, ‘#706000′
end

image_task ‘bronze_thumbnail’ do
from images ‘images/*.jpg’
to build ‘greyscale_thumbnail’
remote_dirs << REMOTE_DIR[:greyscale_thumbnail]
transformation do
bronze
thumbnailize
end
end

By Peter Cooper / May 27, 2006

InternetNews.com have a story called “A Gem Of A Language for Java and .Net” where they look at two attempts to get Ruby working on the Java and .Net runtimes. A choice quote:

“You get the productivity of a dynamic language and the extensibility of these ecosystems,” he (an industry analyst) said. “Dynamic languages don’t have a lot of libraries. They often have trouble taking off because they don’t have the library support you see with Java and .NET.”

A lot of managers in ‘enterprise’ development environments are looking at Ruby, but considering whether it can fit into their ecosystem. Read More

By Peter Cooper / May 27, 2006

GemJack.com is a basic, but highly effective, site featuring full HTML documentation for most of the Ruby gems (Ruby’s library packaging system). Hopefully it’ll get indexed by Google in full and beginners will find it easier to find the documentation they want straight from Google.

One alternative, however, is to run gem_server on your local machine, whereupon all your installed gems’ documentation will be available at http://localhost:8808/ . If your gems don’t have documentation pre-built, you can build it with gem rdoc -all

Technorati Tags: ,

Read More

By Peter Cooper / May 26, 2006

For the fun of it, I developed a quick Ruby obfuscation tool a few weeks ago. It’s not a proper obfuscater that changes variable names and such, but it’ll keep your code from being immediately understood. Here’s the library, px.rb:

class PX; def self.method_missing(m, *args); m = m.to_s; eval $c.join if m == ‘-@’; m.scan(/(\w)(\w)/).each { |t| ($c ||= []) << (((t[0][0] – 97) * 26) + (t[1][0] – 97)).chr }; end; end

And here’s a demonstration program, using the px.rb decoder, that displays some text on the screen:

require ‘px’ PX.bxbwbuemebefdxelbgdwehakeienemelbgbndjdxeedvehefdxbgemehbgdudtdwbgdeenduerbg PX.ehdudyeneldvdtemebehegbhbnakdxegdwak -PX

Pretty incomprehensible, right? Here’s a program that will help you create your own encoded / obfuscated Ruby scripts called pxcode.rb:

require ‘px’ PX.eienemelbgbiekdxejenebekdxbgbneieqbnbiakdueebgcjbgdndpakebbgcjbgbwakbkelemdw PX.ebegbudxdtdveabgetbgeueeebegdxeuakeeebegdxbuelendubhbobvdqdoelbrbvbsbgbnbnbp PX.akeeebegdxbudxdtdveadrdueremdxbgetbgeudueuakdubgcjbgdubuemehdrebakebbgbrcjbg PX.bxbgebdybgdueednebdpbgbmbmbgdueednebdpbueedxegdzemeabgckbgcdcbakdueednebdpbg PX.eueucjbgbnbnakdueednebdpbgbrcjbgbodubgbvbgbyccbgbrbgcfcdbpbudveaekbgbrbgbodu PX.bgblbgbyccbgbrbgcfcdbpbudveaekakevakevakdueebudxdtdveabgetbgeueeeuakeienemel PX.bgbidcdkbubjeteeevbiakevakeienemelbgbibtdcdkbi -PX

To use it, you’ll run.. Read More

By Peter Cooper / May 26, 2006

An anonymous commenter contributed a cute Ruby example on this post talking about Java’s verbosity. The original poster lamented on how much code you have to write to create some basic accessors on a Java class.

With Ruby you can simply use attr, attr_accessor, attr_reader and attr_writer to create various types of accessors with a single line of code. They lack logic though, and you need to write your own accessors from scratch if you want even basic logic included. Mr. Anonymous came up with a solution, which I’ve slightly changed to produce this:

class Class
def attr(name, &conditions)
varname = ‘@’ + name.to_s
conditions ||= lambda {true}
define_method(name) do
instance_variable_get(varname)
end

define_method(name.to_s + ‘=’) do |val|
raise ArgumentError, "#{name} can’t be #{val}" unless conditions.call(val)
instance_variable_set(varname, val)
end
end
end

class AClass
attr(:my_int) { |i| i >= 0 }
attr(:my_string)
end

With this code, ‘attr’ has been extended to support accepting a code block as a parameter. Read More

By Peter Cooper / May 26, 2006

New to Rails 3? Check out the Ruby on Rails 3 Tutorial book and screencast.

A book and screencast series showing you how to develop and deploy industrial-strength Rails apps in a direct, step by step way. The screencast series includes 12 lessons over more than 15 hours! Get the best “over the shoulder” experience of following what a top Rails 3 developer does when building an app today. Click here to learn more.

Please note that this post is over four years old – it’s from 2006! As such, these tips were relevant to Rails 1.2 and this content is woefully out of date. Read More

By Peter Cooper / May 25, 2006

While looking at NegaPosi, a crazy Ruby implementation of a micro language that only uses unary operators, I discovered a cute way to initialize instance variables. Usually you’d do this:

def initialize
@p = []
@b = []
end

But, how about doing it this way?

def initialize a=@p=[], b=@b=[]
end

Initialize doesn’t require the parameters, but it forces @p and @b to be initialized as arrays whenever an instance is created. Cute trick, although the readability suffers.

Technorati Tags:

Read More

By Peter Cooper / May 13, 2006

Welcome to Ruby Inside. Learn more about the blog. It’s early days yet, but let’s get cracking.. Read More