Where is the best place to add methods to the Integer class in Rails?

前端 未结 7 2196
死守一世寂寞
死守一世寂寞 2021-02-10 05:56

Where is the best place to add a method to the integer class in Rails? I\'d like to add a to_meters and to_miles methods.

7条回答
  •  爱一瞬间的悲伤
    2021-02-10 06:43

    If you have your heart set on mucking with the Numeric (or integer, etc) class to get unit conversion, then at least do it logically and with some real value.

    First, create a Unit class that stores the unit type (meters,feet, cubits, etc.) and the value on creation. Then add a bunch of methods to Numeric that correspond to the valid values unit can have: these methods will return a Unit object with it's type recorded as the method name. The Unit class would support a bunch of to_* methods that would convert to another unit type with the corresponding unit value. That way, you can do the following command:

    >> x = 47.feet.to_meters
    => 14.3256
    >> x.inspect
    => #
    

    The best way to handle it would probably be a matrix of conversion types and expressions in the Unit class, then use method_missing to check if a given type can be converted to another type. In the numeric class, use method_missing to ask Unit if it supports the given method as a unit type, and if so, return a unit object of the requested type using the numeric as its value. You could then support adding units and conversions at runtime by adding a register_type and register_conversion class method to Unit that extended the conversion matrix and Numeric would "automagically" pick up the ability.

    As for where to put it, create a lib/units.rb file, which would also contain the monkey_patch to Numeric, then initialize it in config/environment.rb bu requiring the lib/units.rb file.

提交回复
热议问题