向 Rails 中的 Integer 类添加方法的最佳位置在哪里? [英] Where is the best place to add methods to the Integer class in Rails?

查看:57
本文介绍了向 Rails 中的 Integer 类添加方法的最佳位置在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails 中向整数类添加方法的最佳位置在哪里?我想添加一个 to_metersto_miles 方法.

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.

推荐答案

如果您一心想使用 Numeric(或整数等)类来进行单位转换,那么至少要在逻辑上进行并使用一些实数价值.

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.

首先,创建一个 Unit 类,用于存储单位类型(米、英尺、肘等)和创建时的值.然后将一堆方法添加到 Numeric 对应于单元可以具有的有效值:这些方法将返回一个 Unit 对象,其类型记录为方法名称.Unit 类将支持一堆 to_* 方法,这些方法将转换为具有相应单位值的另一种单位类型.这样,您可以执行以下命令:

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
=> #<Unit 0xb795efb8 @value=14.3256, @type=:meter>

处理它的最佳方法可能是在 Unit 类中使用转换类型和表达式的矩阵,然后使用 method_missing 来检查给定类型是否可以转换为另一种类型.在 numeric 类中,使用 method_missing 询问 Unit 是否支持给定的方法作为单元类型,如果支持,则返回一个使用数字作为其值的请求类型的单元对象.然后,您可以支持在运行时添加单位和转换,方法是向 Unit 添加 register_type 和 register_conversion 类方法,扩展转换矩阵,而 Numeric 将自动"获取能力.

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.

至于把它放在哪里,创建一个 lib/units.rb 文件,其中也将包含 Monkey_patch 到 Numeric,然后在需要 lib/units.rb 文件的 config/environment.rb bu 中初始化它.

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.

这篇关于向 Rails 中的 Integer 类添加方法的最佳位置在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆