我想在我的应用程序(运行 Rails 3.2)中覆盖 date_select 表单助手,以:selected
从Rails 4 date_select中引入参数。
覆盖默认的 Rails date_select现在有点老了,但我正在引用它来尝试使其工作。
所以我在一个文件中有以下内容lib/
,包括在底部environment.rb
:
ActionView::Helpers::Tags::DateSelect.class_eval do
#
# Note: Using ActionView::Helpers::DateTimeSelector as suggested in
# linked question doesn't error, but also doesn't seem to do anything.
#
def datetime_selector(options, html_options)
datetime = options[:selected] || value(object) || default_datetime(options)
@auto_index ||= nil
options = options.dup
options[:field_name] = @method_name
options[:include_position] = true
options[:prefix] ||= @object_name
options[:index] = @auto_index if @auto_index && !options.has_key?(:index)
DateTimeSelector.new(datetime, options, html_options)
end
end
但是,当尝试启动我的应用程序时,我看到:
NameError: uninitialized constant ActionView::Helpers::Tags
在控制台中播放时可以确认这一点:
1.9.3-p327 :001 > ActionView
=> ActionView
1.9.3-p327 :002 > ActionView::Helpers
=> ActionView::Helpers
1.9.3-p327 :003 > ActionView::Helpers::Tags
NameError: uninitialized constant ActionView::Helpers::Tags
from (irb):3
from /Users/colin/.rvm/gems/ruby-1.9.3-p327/gems/railties-3.2.11/lib/rails/commands/console.rb:47:in `start'
from /Users/colin/.rvm/gems/ruby-1.9.3-p327/gems/railties-3.2.11/lib/rails/commands/console.rb:8:in `start'
from /Users/colin/.rvm/gems/ruby-1.9.3-p327/gems/railties-3.2.11/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
那么,为什么ActionView::Helpers::Tags
无效,什么时候定义类,以及如何正确覆盖该类以覆盖 datetime_selector 方法?
回答
在 Dan 指出我试图对错误的文件进行猴子补丁之后,解决方案相当简单——这段代码完成了这项工作(放置在初始化程序中):
ActionView::Helpers::InstanceTag.class_eval do
def datetime_selector(options, html_options)
datetime = options.fetch(:selected) { value(object) || default_datetime(options) }
@auto_index ||= nil
options = options.dup
options[:field_name] = @method_name
options[:include_position] = true
options[:prefix] ||= @object_name
options[:index] = @auto_index if @auto_index && !options.has_key?(:index)
ActionView::Helpers::DateTimeSelector.new(datetime, options, html_options)
end
end