The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Module#to_proc h0tness

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
john hume

Posts: 82
Nickname: duelnmrkrs
Registered: Oct, 2005

John Hume is a developer and consultant with ThoughtWorks.
Module#to_proc h0tness Posted: Oct 18, 2008 7:22 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by john hume.
Original Post: Module#to_proc h0tness
Feed Title: El Humidor
Feed URL: http://feeds.feedburner.com/ElHumidor
Feed Description: John D. Hume on Ruby and development with agile teams.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by john hume
Latest Posts From El Humidor

Advertisement

I don't need this right now, so I'm not putting it into any of the codebases I touch. But if I ever do need it, I haven't thought of a reason yet that I shouldn't pull it in.

describe "Module#to_proc" do
  it "provides a proc that mixes the module into the yielded object" do
    
    # Say you've got some stuff,
    
    stuff = ["jimmy", "jane", Object.new]
    
    # and you want to have all that stuff extend a certain Module.
    
    module Fooable
      def foo() "This #{self.class} is fooing"; end
    end
    
    # stuff.each {|thing| thing.extend Fooable } is just so many
    # characters to type!
    
    # With a little hackery in Module, you can do this.
    
    stuff.each &Fooable
    
    # Now all that stuff will have your module mixed in,
    
    stuff.each {|thing| thing.should be_a_kind_of(Fooable) }
    
    # and have interesting new behavior.
    
    stuff.collect {|o| o.foo }.should == [
      "This String is fooing",
      "This String is fooing",
      "This Object is fooing"]
  end
end

Here's all it takes to make it pass, plus some simple memoization so it's cheaper to call.

class Module
  def to_proc
    @to_proc ||= Proc.new {|o| o.extend self }
  end
end

Read: Module#to_proc h0tness

Topic: Running Fast and the Demise of Dynamic Scaffolding in Rails Previous Topic   Next Topic Topic: Four years ago ...

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use