I have the code below from “mechanize gem” [ the file is module.rb].
am a newbie in ruby. Could anyone help me redesign the code below to
use either
(a) block eval OR (b) not use eval at all.
Thoughts ?
class Module
def attr_finder(*syms)
syms.each do |sym|
class_eval %{ def #{sym.to_s}(hash = nil)
if hash == nil
@#{sym.to_s}
else
@#{sym.to_s}.find_all do |t|
found = true
hash.each_key { |key|
found = false if t.send(key.to_sym) !=
hash[key]
}
found
end
end
end
}
end
end
end
It’s pretty reasonable to use eval in the code you provide. I think the
method it defines will be faster because there is no closure created.
But if you really want to avoid it:
class Module
def attr_finder(*syms)
syms.each do |sym|
define_method(sym) do |*args|
val = instance_variable_get("@#{sym}")
return val if args.empty?
hash = args.first
val.find_all do |t|
found = true
hash.each_key { |key|
found = false if t.send(key) != hash[key]
}
found
end
end
end
end
end
It’s pretty reasonable to use eval in the code you provide. I think the
method it defines will be faster because there is no closure created.
+1
In cases like this, when you can use a string eval, it is usually the
best approach. There are cases where you cannot do this b/c you need
access to a local variable.
Please, not to be asking too much, I need to make use of “Hpricot gem”
files. I don’t want to install it as a gem. I copied lib/hpricot/*{all
files} and lib/hpricot.rb to my application.
below is lib/hpricot.rb
begin
require ‘encoding/character/utf-8’
rescue LoadError
end
Please, not to be asking too much, I need to make use of “Hpricot gem”
files. I don’t want to install it as a gem. I copied lib/hpricot/*{all
files} and lib/hpricot.rb to my application.
below is lib/hpricot.rb
begin
require ‘encoding/character/utf-8’
rescue LoadError
end