Forum: Ruby on Rails How to DRY This? (params=>var?)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Wai T. (Guest)
on 2007-04-05 20:40
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]
Luke I. (Guest)
on 2007-04-05 21:07
(Received via mailing list)
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.
Hongli L. (Guest)
on 2007-04-05 21:13
(Received via mailing list)
On Apr 5, 6:40 pm, Wai T. <removed_email_address@domain.invalid> 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.
Wai T. (Guest)
on 2007-04-05 21:27
I see.  Thanks Hongli L..
tonypm (Guest)
on 2007-04-08 15:07
(Received via mailing list)
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
This topic is locked and can not be replied to.