Showing posts with label ruby. Show all posts
Showing posts with label ruby. Show all posts

25 June, 2008

Ruby Needs a StringBuffer

john has written a little post about using a String as a File (really as an IO) in Ruby. He does a great job explaining how StringIOs work for reading characters. They're particularly good for unit tests on IO operations.

What john doesn't mention, however, is that StringIO is only an 'I.' It has no 'O.' You can't do this, for example:

s = StringIO.new
s << 'foo'
s << 'bar'
s.to_s
# => should be "foo\nbar"
# => really is ''

Ruby really needs a StringBuffer just like the one Java has. StringBuffers serve two important purposes. First, they let you test the output half of what Ruby's StringIO does. Second, they are useful for building up long strings from small parts -- something that Joel reminds us over and over again is otherwise very very slow.

So I wrote a StringBuffer, but it's not very good, and it's not very fast. What we need is one written in C in the core Ruby library. Now that will help Rails scale.

27 March, 2008

New Gem: Avatar

I released Avatar version 0.0.3 today. This gem offers avatar support for a variety of sources. It's not Rails-specific, but to use it in a Rails app, do something like the following.

In app/helpers/people_helper.rb:

class PeopleHelper
  include Avatar::View::ActionViewSupport

  def default_avatar_url(size)
    req = controller.request
    "#{req.protocol}#{req.host_with_port}#{image_path("/images/avatar_default_#{size}.png")}"
  end
end

app/views/people/show.html.erb:

<%= avatar_tag(@current_user, :size => 40, :default => default_avatar_url(:small) %>

The default settings will check for a Gravatar for @current_user.email. There are other implementations, including one that works with the file_column plugin. I'll be happy to add more implementations; the project is hosted on GitHub.

19 February, 2008

with_modules_unavailable and some Module helpers

I've been trying to test a new Rails plugin (stay tuned!), and I've found that I need to have certain Modules unavailable. This is useful when you need to test that missing Modules will raise errors or if you have behavior conditional on what gems are installed.

I wanted something like:

...
with_modules_unavailable(Foo, Bar::Baz::Goo) do
  test stuff
end

To get this working, just put the following in your test_helper.rb (this version requires Inflector):

Module.class_eval do
  
  def defining_module
    chain = self.to_s.split(/\:\:/)
    chain.pop
    if chain.empty?
      Object
    else
      chain.join('::').constantize
    end
  end
  
  def simple_name
    self.to_s.split(/\:\:/).pop
  end
  
end

Test::Unit::TestCase.class_eval do

  def with_modules_unavailable(*mods, &block)
    Thread.exclusive do
      mods.each do |mod|
        mod.defining_module.send :remove_const, mod.simple_name.to_sym
      end
      yield block
      mods.reverse.each do |mod|
        mod.defining_module.send :const_set, mod.simple_name.to_sym, mod
      end
    end
  end
  
end

You can test that it works with:

def test_with_modules_unavailable
  with_modules_unavailable(ActiveRecord::Base) do
    assert_raise(NameError) { ::ActiveRecord::Base.class_eval { } }
  end
  assert_nothing_raised { ::ActiveRecord::Base.class_eval { } }
end

17 February, 2008

Updates to active_support_hacks

I've made a couple of updates to my active_support_hacks

First: DateRange#include?(other)

This accepts a Date, Time or another TimeRange. It assumes inclusive range ends

4.days.ago.until(1.day.ago).include?(2.days.ago)                    #  => true
4.days.ago.until(1.day.ago).include?(3.days.ago.until(2.days.ago)   #  => true
5.hours.from_now.until(10.hours.from_now).include?(6.days.from_now) #  => false

Second: Pretty Date Formatters

These generate human-readable times and dates, like "9 hours from now" and "earlier this week"

f = ActiveSupport::CoreExtensions::Time::PrettyNumericDateFormatter.new
f.call(5.hours.ago)       # => "5 hours ago"
f.call(37.days.ago)       # => "1 month ago"

f = ActiveSupport::CoreExtensions::Time::PrettySimpleDateFormatter.new
f.call(5.hours.ago)       # => "earlier today"
f.call(55.days.from_now)  # => "later this year"

You can load these into the ActiveSupport formatting code like so:

require 'active_support/core_ext/time/pretty_numeric_date_formatter'
require 'active_support/core_ext/time/pretty_simple_date_formatter'

#each formatter must either respond to #call(Date) and #call(Time) or be a String for strftime

formatters = {
  :pretty_numeric => ActiveSupport::CoreExtensions::Time::PrettyNumericDateFormatter.new,
  :pretty_simple => ActiveSupport::CoreExtensions::Time::PrettySimpleDateFormatter.new
}
formatters[:pretty] = formatters[:pretty_numeric]
formatters[:default] = formatters[:pretty]

ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(formatters)
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(formatters)

I have that in my Rails app in /config/initializers/date_formats.rb. If you don't want to override the default formatting of dates, don't include the formatters[:default] = formatters[:pretty] line. By including a [:default] in the hash, all ActionViews will automatically use this formatter.

14 February, 2008

ActiveSupport additions: TimeRange and Distance

I've created some utility classes that I use in many of my projects. I've broken them out into a Rails plugin, but they should really be part of ActiveSupport.

First: TimeRange

t = 5.minutes.ago.until(1.second.ago)
s = 10.minutes.ago.until(3.minutes.ago)
overlap = t & s
overlap.start_time # => 5.minutes.ago
overlap.end_time   # => 3.minutes.ago

Second: Distance

4.miles + 6.miles  # => 10.miles
5.yards.to_feet    # => 15.feet
12.miles.in_km     # => 19.312128.km
12.miles.as_km     # => 19.312128.km
2.meters > 2.yards # => true

Eventually, I plan on moving some of GeoKit into some sort of ActiveRecord::DistanceSupport in the plugin.

If you want the plugin, you can get it at https://svn.u-presence.com/svn/plugins/active_support_hacks/ (Username guest, no password). I'd love any other suggestions or comments on the utilities.

09 February, 2008

Hacking Rubygems' #require, #require_gem, #gem

I have some old gems in my latest Rails app, and Rubygems has changed its syntax since those gems were built. The gems have require_gem in them, but the newest version of Rubygems doesn't add that command to Kernel, so you get NoMethodErrors when the gem loads. This simple hack in config/environment.rb will fix it:

# hack rubygem's change to #require:
Kernel.class_eval do
  def require_gem(*args)
    gem *args
  end
end
I have it right before require File.join(File.dirname(__FILE__), 'boot') in case my config/environments/xxx.rb loads an old gem.

30 January, 2008

First Ruby Gem!!!

I've just created my first Ruby Gem out of the with_probability code I've been working on. Simply

sudo gem install nondeterminism
Much thanks also to the initial author of the Sometimes Pastie Any problems with or suggestions for the gem? Join the Google Ruby-Nondeterminism Group

29 January, 2008

with_probability

In fuzzing my database for testing (see Fuzzing your Database and Faker), I've found the following to be very useful:

Object.class_eval do
  def with_probability(prob, &block)
    if rand <= prob
      block.call 
      return ProbabilisticDoer::Done.new
    else
      return ProbabilisticDoer::NotDone.new
    end
  end
end

module ProbabilisticDoer
  class NotDone
    def else_with_probability(prob, &block)
      with_probability(prob, &block)
    end
    def else(&block)
      with_probability(1, &block)
    end
  end
  
  class Done
    def else_with_probability(prob, &block)
      return self
    end
    def else(&block)
      return self
    end
  end
end

With that, you can do things like

u = User.create(...)
with_probability(9/10.0) do
  u.stuff_that_most_users_should_do
end

with_probability(0.01) do
  u.stuff_that_very_few_users_should_do
end.else_with_probability(0.2) do
  u.stuff_that_some_but_none_of_the_above_users_should_do
end.else do
  u.stuff_the_rest_of_the_users_should_do
end

06 July, 2007

has_many_polymorphs and the open-closed principle

I like has_many_polymorphs. I would love it if only it obeyed the open-closed principle.

Let's say I have a PetOwner model, and I want it to have_many pets polymorphically.

has_many_polymorphs lets you do this:

class PetOwner < ActiveRecord::Base
  has_many_polymorphs :from => [:dogs, :cats, :fish]
  ...
end

But what if I later decide I want to add a Ferret class? In addition to

class Ferret < AbstractPet
  ...
end

I also have to change PetOwner:
class PetOwner < ActiveRecord::Base
  has_many_polymorphs :from => [:dogs, :cats, :fish, :ferrets]
  ...
end

It would be really lovely if has_many_polymorphs could just tell what has inherited from AbstractPet. There's no reason you can't do this (in fact, I did before I wrote this post), but there's a timing problem: all of the inherited classes have to load before PetOwner does. The has_many_polymorphs ... call only happens when PetOwner is first included, so all of those other classes have to have already registered themselves with AbstractPet (simply by inheriting from it) by then; unfortunately, there's no good way to guarantee class load order without major hacking at the environment.

Sometimes we just have to put up with not-the-best. Alas.

01 July, 2007

and the test_spec_on_rails journey continues

Test/Spec has a wonderful - if largely unnoticed - feature: you can specify the superclass of contexts. The default is the ole' Test::Unit::TestCase, but that won't always do.

Let's say, hypothetically, you wanted to write some integration tests for your not-quite-shiny Rails app. You'd use ApplicationController::IntegrationTest, right? That way you can do things like get "/posts/34.html" and it would look up the routings and just do the right thing. Awesome.

Except... things aren't quite so simple when using test/spec. Therefore, I bring you an illustrious, illustrative example:

require File.dirname(__FILE__) + '/../test_helper'

class UserStoriesTest < ActionController::IntegrationTest
 fixtures :people, :openid_authentications, :password_authentications
 context "User Stories", ActionController::IntegrationTest do
   context "a person coming to the site to log in", ActionController::IntegrationTest do
     specify "should see the welcome page" do
       get '/'
       template.should.be 'welcome/index'
       status.should.be 200
     end
     specify "should be able to successfully log in with email and password..." do
       post_via_redirect '/login.html', {:email => 'pete.thomas@xahoo.com', :password => 'test'}
       template.should.be 'people/home'
       status.should.be 200
     end
   end
 end

end

test_spec_on_rails continued...

Yesterday, I was very happy because all my controller tests (using test/spec, of course) were passing individually.

Today I decided to run rake test:functionals just to make sure they played well together. CRASH! BOOM! OTHER LOUD NOISES!

The problem, after two hours of debugging, is that I was creating the same context in different controllers. DocumentationControllerTest had a "A guest" context, and so did "AccountControllerTest" and "WelcomeControllerTest"

Test/spec is perfectly happy to merge these . . . I just didn't realize it merged them. I assumed that it would scope the context to its parent TestClass. No such luck.

The solution is quite easy, and really not all that bad practice anyway: scope your contexts manually. For example:

class WelcomeControllerTest < Test::Unit::TestCase
 context "The Welcome Controller" do
   context "A guest" do
     ...
   end
   context "A logged-in user" do
     ...
   end
 end
end