damoiser
damoiser

Reputation: 6238

Rails - use object oriented "advanced"

I would like to maintain my code DRY, then I want to transform this pseudo-code:

def aMethod
  a = aModel.find(2)
  b = a.getVariable
  a.setVariable = c
end

in something like this

def aMethod
  anotherMethod(aModel, getVariable)
end

def anotherMethod(model, var)
  a = model.find(2)
  b = a.var
  a.var = c
end

In my tests, seems that there is no problem for the model, but for the getVariable (i.e. accessing the variable of the model) it doesn't work: undefined local variable or method

Any ideas?

Upvotes: 0

Views: 75

Answers (1)

Dave Newton
Dave Newton

Reputation: 160291

You likely want to use send, if I understand what you're trying to do, e.g.,

def anotherMethod(model, var_sym)
  a = model.find(2)
  b = a.send(var_sym)
  a.send("#{var_sym}=", c)
end

anotherMethod(aModel, :getVariable)

(With the caveat that I don't know what a, b, or c are, or should do, since they're locals in the OP.)

Upvotes: 3

Related Questions