Dynamic Method Calls

M

Matt Mencel

Right now I have some inefficient code that looks like this...

LdapAccount is my model.... and record.attributes is a hash of attribute name,value pairs.


records.each do |record|
LdapAccount.create:)uid => record.attributes["uid"].to_s) do |c|
c.buildingname = record.attributes["buildingName"].to_s if record.attributes.has_key?("buildingName")
c.cn = record.attributes["cn"].to_s if record.attributes.has_key?("cn")
c.department = record.attributes["department"].to_s if record.attributes.has_key?("department")
c.displayname = record.attributes["displayName"].to_s if record.attributes.has_key?("displayName")
c.employeetype = record.attributes["employeeType"].to_s if record.attributes.has_key?("employeeType")
c.givenname = record.attributes["givenName"].to_s if record.attributes.has_key?("givenName")
c.homedirectory = record.attributes["homeDirectory"].to_s if record.attributes.has_key?("homeDirectory")
c.mail = record.attributes["mail"].to_s if record.attributes.has_key?("mail")
end
end


There's probably 20 or more attributes I'll eventually be checking...I'm working with tens of thousands of records....and not all records have values for every attribute. So rather than do all the extra wasted work, I'd really like to be able to do something simpler like this...

records.each do |record|
LdapAccount.create:)uid => record.attributes["uid"].to_s) do |c|
record.attributes.each_pair do |k,v|
c.k = v
end
end
end

...but I get...
undefined method `k=' for #<LdapAccount:.....>

Did a little research and read about the send method....so I tried this...

c.send(k = v)


...but I get... (in this case the String value of v = "smtp.wiu.edu")
["smtp.wiu.edu"] is not a symbol


So I'm not sure I understand how to use the send method in this case. Can anyone offer some insight? Am I headed in the right direction or is there a better way to do this.

Thanks,
Matt
 
A

Andrea Dallera

Hei Matt,

try c.send(k, v)
I haven't tried that myself but it looks like what you want to accomplish.

Bye!
 
A

Andrea Dallera

Whoopsie, i'm really sorry. It should be something like:

c.send("#{k}=".to_sym, v)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top