snax

ruby performance

truth accessors in rails

It might be nice to be able to ask obj.variable? for any accessor-defined @variable. Aaron Pfeifer has a big solution with API changes (use battr instead of attr), and non-standard truth values. Yurii Rashkovskii has a small solution with API changes (append ? to the variable name). But we can do better than this .

incredible shrinking plugin

Here’s a smallest solution without API changes.

class Class
  [:attr, :attr_accessor, :attr_reader].each do |acc_name|
    unbound = self.send(:instance_method, acc_name)
    define_method(acc_name) do |*vars|
      vars.each do |var|
        next unless var.is_a? Symbol or var.is_a? String
        define_method("#{var}?"){!instance_variable_get("@#{var}").blank?}
      end
      unbound.bind(self).call *vars                
    end
  end
end

Just dump it in environment.rb or something. Call the accessors as you normally would, and variable? will be there when you need it.

Not all core extensions have to be plugins, or be large and complicated. All we want here is a shortcut to !obj.variable.blank?.

By using blank? (contrary to Aaron’s plugin) we stay consistent with the rest of Rails. If "f" is supposed to mean false it should be parsed as such when the object is built. Otherwise we have to cross our fingers and hope we remember about the non-standard, non-localized check buried in the plugin source.

August 20, 2007

1 comment

Mislav says (January 05, 2007):

Very nice!

Comments are closed.