简体   繁体   English

覆盖默认的Rails date_select

[英]Overriding default Rails date_select

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). 所以我想要做的是覆盖默认的date_select方法(我想做一个'可选/未指定的'日期输入)。 What I've tried so far is this: 到目前为止我尝试过的是:

lib/overrides.rb 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: 然后我在environment.rb的底部要求'覆盖'但是在启动WEBrick时我收到此错误:

~/.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! 〜/ .rvm / gems / ruby​​-1.9.2-p0 / gems / activesupport-3.0.0 / lib / active_support / dependencies.rb:479:在`load_missing_constant'中:ActionView :: Helpers没有丢失常量DateTimeSelector! (ArgumentError) (引发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. 上面的错误似乎暗示它找不到DateTimeSelector类,但我已经看到了〜/ .rvm / gems / ruby​​-1.9.2-p0 / gems / actionpack-3.0.0 / lib / action_view中的代码/helpers/date_helper.rb我认为我的模块层次结构正确。 Is it because it's a private Rails class? 是因为它是一个私有的Rails类吗?

Any thoughts are most welcome :) 欢迎任何想法:)

In Ruby doesn't exist the concept of private class. 在Ruby中不存在私有类的概念。 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. 事实上,Ruby为您提供了重新打开类和“补丁”方法的能力,但这并不意味着您应该为这种类型的自定义执行此操作。

You should never make these chances to the Rails codebase unless you really know what you are doing. 你永远不应该把这些机会带到Rails代码库,除非你真的知道你在做什么。 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. 正确的方法是定义一个新的帮助器并构建自己的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM