views:

55

answers:

1

So what I'd like to do is to override the default date_select method (I'd like to make an 'optional / unspecified' date input). What I've tried so far is this:

lib/overrides.rb

ActionView::Helpers::DateHelper::DateTimeSelector.class_eval do
  def build_selects_from_types(order)
    select = ''
    order.reverse.each do |type|
      separator = separator(type) unless type == order.first # don't add on last field
      select.insert(0, separator.to_s + send("select_#{type}").to_s)
    end
    select.insert(0, '<p>HI!!</p>') # or whatever...
    select.html_safe
  end
end

I then required 'overrides' at the bottom of environment.rb but when starting WEBrick I get this error:

~/.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:479:in `load_missing_constant': ActionView::Helpers is not missing constant DateTimeSelector! (ArgumentError)

So I obviously don't really know what I'm doing but this seems like a reasonable thing to attempt at least.

The error above seems to imply that it can't find the DateTimeSelector class but I've peered at the code in ~/.rvm/gems/ruby-1.9.2-p0/gems/actionpack-3.0.0/lib/action_view/helpers/date_helper.rb and I think I've got the module hierarchy right. Is it because it's a private Rails class?

Any thoughts are most welcome :)

+3  A: 

In Ruby doesn't exist the concept of private class. Classes are never private.

The reason for the error is because the path is invalid. It should be

ActionView::Helpers::DateTimeSelector

not

ActionView::Helpers::DateHelper::DateTimeSelector

BTW, what you are trying to do is absolutely a bad idea. The fact that Ruby gives you the power of reopening classes and "patch" methods, doesn't mean you should do this for such this kind of customizations.

You should never make these chances to the Rails codebase unless you really know what you are doing. The risk is to break things that depends on this method.

The right way to go is do define a new helper and build your own logic.

Simone Carletti
Oops, yes I missed the end of the DateHelper module. I'm glad it didn't work though as it meant I asked the question here and gave you the chance to tell me it's a dumb idea in the first place :)
Jerome
It seemed like a good idea because there's a lot of excellent code and I just needed to tweak a teeny bit. I absolutely take your point though and I guess I can re-use certain methods so I don't have to completely re-invent the date selection wheel.Thanks Simone.
Jerome
@Jerome The helper is created as a Class. You can always create a class and inherit from DateTimeSelector, so that you will have all the original methods and you can easily override them without affecting the original source.
Simone Carletti
Thanks again Simone. Believe it or not I'm a pretty proficient C# programmer of some years but a lot of this Rails stuff still feels like black magic, even though many core concepts are the same, of course :)
Jerome