07
Sep
09

groovy and ruby equivalents:evaluating in the context of an object



Let’s say you have a class that has a debug method, and you call it repeteadly:


obj.debug("debugstring")
obj.debug(debug_val)
obj.debug(another_debug_val)

You could make this shorter by using the with method. This will evaluate the code inside the block in the context of the object it was called upon:


obj.with {
   debug("debugstring")
   debug(debug_val)
   debug(another_debug_val)
}

This can make your code cleaner and simpler to understand.

Here’s the Ruby equivalent: instance_eval, and a snippet of code showing how to use it:


File.open("some.file") do |file|
   file.instance_eval do
      puts "this goes into the file"
      puts "same as this"
   end
end

By calling instance_eval, the puts method calls become file.puts. Nice, right?

About these ads

1 Response to “groovy and ruby equivalents:evaluating in the context of an object”


  1. September 8, 2009 at 04:42

    As for Ruby code, there is a little trick that i would like to share with you:

    A one can think of defining the ‘open’ method in File class like this:

    class File
    def self.open2(path,&block)
    f=File.new(path)
    f.instance_eval(&block)
    f.close
    end
    end

    But then doing things like:

    File.open2(“path_to_file”){ puts path}

    Won’t work!

    cause the ‘path’ method inside the block is evaluated inside the File class context.

    To overcome such problems it’s better to redefine the method ‘open2′ as the follows:

    class File
    def self.open2(path,&block)
    f=File.new(path)
    block.arity < 1 ? f.instance_eval(&block) : block.call(pdf)
    f.close
    end
    end

    But then you have to pass the current file object as a param when you need to call instance methods:

    File.open2("path_to_file"){|file| file.puts path}


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Blog Stats

  • 178,046 hits

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: