catmal
catmal

Reputation: 1758

Rails use attributes as string in method

I am using the gem Alchemist to make unit conversions. Given this working in my model:

class Item < ApplicationRecord
    def converted
        quantity = 1
        quantity.kg.to.g
    end
end

How do I make kg and g dynamic? Like:

quantity.unit_purchase.to.unit_inventory

unit_purchase and unit_inventory are attributes (strings) of the class, corresponding to values such as kg, g and so on.

So perhaps something like:

x = self.unit_purchase
y = self.unit_inventory
quantity.x.to.y

But I'm having hard time to find the syntax.

Upvotes: 0

Views: 339

Answers (1)

tadman
tadman

Reputation: 211740

If you really want to do this the hard way:

unit_purchase = :kg
unit_inventory = :g
quantity.send(unit_purchase).to.send(unit_inventory)

That depends on knowing with absolute certainty that the two arguments are valid and aren't something hostile supplied by the user.

A safer way is to define a more arbitrary conversion method like:

quantity.convert(from_unit: unit_purchase, to_unit: unit_inventory)

Where that can check the arguments accordingly and raise on unexpected values.

Upvotes: 1

Related Questions