views:

93

answers:

1

I'm trying to fool a very complex black box into displaying some floats differently (it's the Gruff graphing library, so this is being rendered to an image).

In the console, I can paste this:

  logger = RAILS_DEFAULT_LOGGER
  logger.debug "Here's a float #{455.67.to_s}"
    eval %{class Float
    def to_s_with_time
      h = (self / 60).to_i
      m = self.to_i % 60
      return h.to_s + ':' + m.to_s
    end
    alias_method_chain :to_s, :time
    end
    }
    logger.debug "Here's another #{455.67.to_s}"

And I'll see

Here is a float 455.67
Here is another 7:35

But if I paste the same code into a controller, I see

Here is a float 455.67
Here is another 455.67

Why can't I replace Float.to_s within a controller? I will also accept answers to the question "What's a better way to accomplish this?"

A: 

If you want to replace the behavior of Float#to_s, you could try adding your monkeypatch to the Float class in an initializer. This will however patch Float#to_s globally within your Rails app.

config/initializers/float_patch.rb:

class Float
  def to_s
    h = (self / 60).to_i
    m = self.to_i % 60
    h.to_s + ':' + m.to_s
  end
end

You could also make a similar initializer to patch the gruff classes/methods if you you don't want to be so broad as to patch a core class like Float.

rnicholson