Overriding default Rails date_select

那年仲夏 提交于 2019-12-24 10:39:04

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/4007675/overriding-default-rails-date-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!