How to DRY This? (params=>var?)

Hi everyone,

Is it possible to dry this code?

recipients = params[:mail][:recipients]
from = params[:mail][:from]
subject = params[:mail][:subject]
email_body = params[:mail][:email_body]
user = params[:mail][:user]

It probably depends on what you’re doing with it.
If this is going into a model, models accept a hash as an argument to
new
(or to update_attributes, for that matter) such that you could do
Model.new(params[:mail]),
and it would auto-populate the fields.
If it’s not, and you just need all those variables to pass as arguments
to
something else, then you probably don’t need to pull them out into local
variables.
But, if you were absolutely 100% needing to DRY that code up, you could
do
something similar to this:
class MailInfo
def initialize(options = {})
options.each do |key, val|
self.instance_variable_set("@#{key}", val)
self.class.class_eval “attr_accessor :#{key}”
end
end
end
Then do
m = MailInfo.new(params[:mail])
and you should be able to do
m.email_body
m.recipients
etc.

On Apr 5, 6:40 pm, Wai T. [email protected] wrote:

Hi everyone,

Is it possible to dry this code?

recipients = params[:mail][:recipients]
from = params[:mail][:from]
subject = params[:mail][:subject]
email_body = params[:mail][:email_body]
user = params[:mail][:user]

mail = params[:mail]
recipients = mail[:from]
subject = mail[:subject]

That saves you some typing.

But if you want to put your hash variables in local variables, then
you can’t. Well, actually, you can, by using eval. But that’s very,
VERY evil and will open the infinite floodgate of security problems.

Luke,

thanks for that snippet. I find that seeing these little titbits of
code from time to time really helps. They become seeds that later
spring to life when you want to do something and dont quite know how.
The problem I find is either remembering these things, or knowing how
to put them somewhere that I can remember to find them. Thank
goodness for Google.

tonypm

I see. Thanks Hongli L…