0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

unit_purchase comes from database. It's an attribute on the current class. Why would I set it to kg? That makes it static. The second solution does not follow syntax required by the Gem
I updated the question with what I have been trying before posting the question.
The 2 arguments are always valid as the user just enters the item and each item has unit_purchase and unit_inventory set correctly by default.
@Catmal I'd be a lot more paranoid than that. Do unit_purchase or unit_inventory ever come anywhere near user input? Are you sure that will always be the case? Do you have an explicit whitelist somewhere to ensure that the units will never conflict with a "real" method name? You can bob for apples in a bucket of fishhooks if you want but why risk it when there are safer options?
@Catmal just because the U/I constrains these values does not mean you cannot make a request from outside the U/I via mechanisms like curl, postman, etc. The values should at a minimum be validated in the model before saving and certainly validated before transformation when using a send mechanism.
|

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.