Hacktastic! lazy_attr_accessor & lazy_attr_reader

Posted by Luke Pillow Thu, 28 Aug 2008 08:56:00 GMT

Whether or not you agree with the use of lazy initialized attributes, you’d probably agree that writing the accessor method can be a bit tedious at times; especially if you’re used to Ruby’s attr_accessor, attr_reader, and attr_writer methods.

This Hacktastic entry introduces a couple nice (at least fun to write) little Ruby class methods (based on Jay Fields’ blog entry, "Ruby: Lazy Initialized Attributes")  to assist with lazy initialized attribute declarations.

 Let’s take a quick look at how one might use  lazy_attr_accessor & lazy_attr_reader

class Foo
  lazy_attr_accessor :bar => [], :woot => :bam
end
 
foo = Foo.new
puts "Before = #{foo.bar.inspect}" # Before = []
foo.bar << 2
puts foo.woot # bam
foo.woot = :wooooooooot
puts foo.woot #
wooooooooot puts "After = #{foo.bar.inspect}" # After = [2]

And the hack in all it’s glory…

class Object   
  def self.lazy_attr_reader(hsh)
    hsh.each do |method_name, default_value|
      self.send :define_method, method_name.to_sym do
        var_name = "@#{method_name}"
        instance_variable_set(var_name, default_value) unless instance_variable_defined? var_name
        instance_variable_get var_name
      end
    end
  end
# creates both lazy_attr_reader and attr_writer 
  def self.lazy_attr_accessor(hsh)
    attr_writer *hsh.keys
    lazy_attr_reader hsh
  end
end

I’m not claiming this is a best practice, or even the best way to do this so feel free to share any suggestions you might have.

Enjoy!

"Get Rich Quick with Flex and Rails"

Posted by Luke Pillow Wed, 27 Aug 2008 09:08:00 GMT

If you’re looking for anything finance related then you’ve come to the wrong place.

if you’re interested in using Adobe Flex and Ruby on Rails then I’d encourage you to check out the slides and example project from my presentation.

Presentation slides: http://docs.google.com/Present?docid=dgv7jftw_76fs6mch…
Example project:  http://github.com/pillowfactory/kcrug_address_book

Other useful links

RubyAMF project:  http://rubyamf.googlecode.com
RubyAMF::Quickly:  http://github.com/pillowfactory/rubyamf_quickly

Thanks to everyone who attended this month’s KCRUG gathering

Musical Tribute To Ruby 3

Posted by Luke Pillow Sat, 23 Aug 2008 14:52:00 GMT

I thought this might be kind of fun.  I’d love to hear everyone’s suggestions to add to this fine SeeqPod playlist.

Enjoy!


SeeqPod - Playable Search