I am generating some methods on the fly. The method body varies based on a certain criteria. I was relying on class_eval to generate conditional code.
%Q{
def #{name}
#{
(name != "password") ? "attributes[:#{name}]" :
"encrypt(attributes[:#{name}])"
}
end
}
Recently I have started using define_method. How do I generate conditional code blocks while using define_method?
Edit 1
Here are the possible approaches that I have considered:
1) Checking the name on during run time:
define_method(name) do
if name == password
decrypt(attributes[name])
else
attributes[name]
end
end
This is not a preferred method as the check is done during run time.
2) Conditionally defining the entire method.
if (name == "password")
define_method(name) do
decrypt(attributes[name])
end
else
define_method(name) do
attributes[name]
end
end
This approach has the disadvantage of having to repeat the code block just change a small part (as my actual method has several lines of code).