I don’t understand class_eval.
class Module
def attr_ (*syms)
syms.each do |sym|
class_eval %{def #{sym}= (val)
@#{sym} = val
end}
end
end
end
What does the % mean?
What does class_eval do?
And where is (val) coming from?
The short answer is: you probably want to avoid using
class_evallike this.Here’s an explanation of your code:
The
%{hello}is just another way to write a string literal in Ruby, without having to worry about escaping double or single quotes within the string:The
valin your code is an argument of the method being defined.The
class_evalis used to define some methods by computing the text one would write to do the definition and then evaluating it. It is not necessary here, BTW. An equivalent code would be:This is just equivalent to the builtin
attr_writer.Update: There can actually be a significant difference between the two…
The
class_evalversion is vulnerable if you can’t trust the argumentsyms. For example:The
class_evalversion will print “I can execute anything here” twice, proving it can execute anything. Thedefine_methodversion won’t print anything.This type of code was pivotal to create major vulnerability for all installed Rails apps.