blazeP
blazeP

Reputation: 91

Rails - model attribute as a variable in function

I think it is really basic question, but I cannot find solution.

I have simple help method:

def getProperNutrientValue(meal)
    result = 0
  if meal.ingredients.empty?
    result
  else
    meal.ingredients.each do |i|
      result += (i.quantity * @meal.products.find(i.product_id).calorific) / 100
    end
    result
  end
end

Where "calorific" is an attribute in Product model.

class Product < ActiveRecord::Base
  has_many :ingredients
  has_many :meals, :through => :ingredients

  validates :calorific, :numericality => true, :allow_nil => true
  validates :water, :numericality => true, :allow_nil => true

I want to DRY this function, and set attribute as a variable. Then I will be can use this function for example for water attribute. So I want to achieve something like that:

def getProperNutrientValue(meal, attribute)
    result = 0
  if meal.ingredients.empty?
    result
  else
    meal.ingredients.each do |i|
      result += (i.quantity * @meal.products.find(i.product_id).attribute) / 100
    end
    result
  end
end

But of course it doesn't work... How can I fix it?

Upvotes: 2

Views: 206

Answers (1)

Maxim Pontyushenko
Maxim Pontyushenko

Reputation: 3053

You can use send(method_name) method. I don't understand the logic behind using @meal variable. Either way there are some options to improve your code, for example:

def getProperNutrientValue(meal, attribute)
  result = 0
  meal.ingredients.each do |i|
    result += (i.quantity * @meal.products.find(i.product_id).send(attribute).to_i) / 100
  end
  result
end

getProperNutrientValue(meal, :calorific)

Upvotes: 2

Related Questions