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

前端 未结 7 1082
面向向阳花
面向向阳花 2021-02-10 06:19

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:44

    Realize the question is old, but I think the clearest way would be to make a Distance class with two attributes @length and @unit.

    You'd just need a conversion hash, probably as a class variable of Distance:

    class Distance
    
      @@conversion_rates = {
        meters: {
          feet: 3.28084,
          meters: 1.0
        }
      }
    
      def to(new_unit)
        new_length = @length * @@conversion_rates[@unit][new_unit]
        Distance.new( new_length, new_unit ) 
      end
    
    end
    

    And it would look kinda like:

    Distance.new(3, :meters).to(:feet)
    

    which i honestly think looks better than

    3.meters.to_feet
    

提交回复
热议问题