JP Richardson
JP Richardson

Reputation: 39395

How can I dynamically add a method to the Math class in Ruby on Rails?

I am trying to add the following method to the Math class in Ruby on Rails:

class Math
  def self.round_with_precision(number, precision)
    scalar = 10.0 ** precision
    number = number * scalar
    number = number.round
    number = number / scalar
    return number;
  end
end

I then added the following to my environment.rb:

require 'lib/math'

When I open up the Rails console I get the following error: './lib/math.rb:2:TypeError Math is not a class'

It seems like I'm overlooking something very simple.

Any thoughts?

Thanks in advance for your help.

Upvotes: 1

Views: 1178

Answers (3)

Zach Langley
Zach Langley

Reputation: 6786

If you use instance_eval, you don't have to worry about whether to use class or module:

Math.instance_eval do
  def round_with_precision(number, precision)
    scalar = 10.0 ** precision
    (number * scalar).round / scalar
  end
end

Upvotes: 0

Matt Darby
Matt Darby

Reputation: 6324

You can place the file containing this code in config/initializers and it will automatically be included. ~ Just a FYI.

Upvotes: 2

Pedro Henriques
Pedro Henriques

Reputation: 1736

Math is a module, just rename class to module.

Upvotes: 9

Related Questions