Archive for the 'Ruby' Category

Ruby recipie: extending methods without loose the original code

Supose you want to extend the method of a class called Attachment.

# original_file.rb

class Attachment
  def method_to_extend
    puts "The original code"
  end
end

If we try to rewrite the method, older code gets lost, but instead we want it to be executed with our code extension

We want to achieve something like the following:

class Attachment
  def method_to_extend
    puts "The original code"
    puts "My extension code!"
  end
end

But the original code is part of a library we cannot change directly.

The best way I found is to write an alias_method with the original method code and rewrite the method adding the desired code

# extension_file.rb

require 'original_file'
class Attachment
  alias_method :source_method_to_extend, :method_to_extend
  def method_to_extend
    source_method_to_extend
    puts "My extension code!"
  end
end

Building ruby on a separate folder

I had installed ruby throw macports but I want to update a newer version. So I build it.


iMac:~ ruby$./configure cialis pills –-prefix=/opt/ruby_dir \
–-enable-shared \
–-enable-pthread \
–-enable-install-doc && make
iMac:~ ruby$sudo make install

It seems to work well, but when I have tried to use irb it breaks with the following error:


iMac:~ ricard$irb
dyld: NSLinkModule() error
dyld: Symbol not found: _rl_filename_completion_function
Referenced from: /opt/derma/lib/ruby/1.8/i686-darwin8.10.1/readline.bundle
Expected in: flat namespace

Trace/BPT trap

The solutions I have found it’s easy.

Consists in build ruby –-with-readline-dir as follows:

iMac:~ ruby$./configure –-prefix=/opt/ruby_dir \
–-enable-shared \
–-enable-pthread \
–-with-readline-dir=/usr/local \
–-enable-install-doc && make
iMac:~ ruby$sudo make install

And that’s it.

Note:
To be able to use new ruby compilation in an easy way it’s a good idea to change PATH.


iMac:~ ruby$cd
iMac:~ ricard$echo '' >> .bash_login
iMac:~ ricard$echo 'export PATH="/opt/ruby_dir/bin:$PATH"' >> .bash_login