0

Basically I'm doing a find an replace over a set of text with data from the db, but the replacement tags are generated by the user and can be any of a huge selection.

How do you access a model record when the field name is in a variable

Normal access is

var = model.field_name

But in my code, I would like to do something like this

replacement_tags.each do |tag|
  content = content.gsub(/tag/, model.|access attribute with same name as tag|
end

so if tags were firstname, lastname the block would run gsub for model.firstname and model.lastname consecutively.

I don't mind if I'm going about this the wrong way, as long as there is some way to achieve these results

1 Answer 1

4

When you're calling instance methods in Ruby, you are not calling anything, you're sending messages to the receiver.

user.first_name can be read as "send message to this user object that asks it to return its first name"

Equipped with this knowledge and this documentation, you can easily write your code as

replacement_tags.each do |tag|
  content = content.gsub(/tag/, model.send(tag.to_sym))
end
Sign up to request clarification or add additional context in comments.

2 Comments

You may want to use model.__send__(tag.to_sym) in case .send was overriden
Thanks to you both. That's perfect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.