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

前端 未结 7 2200
死守一世寂寞
死守一世寂寞 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:42

    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
    

提交回复
热议问题