覆盖Rails date_select表单助手

时间:2013-01-16 13:00:28

标签: ruby-on-rails ruby-on-rails-3.2

我想覆盖我的应用中的date_select表单助手(运行Rails 3.2),从Rails 4 date_select引入:selected参数。

Overriding default 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

1 个答案:

答案 0 :(得分:0)

ActionView::Helpers::Tags是Rails 4中的新功能(你链接到rails master分支,这是4.0分支),你正在使用Rails 3.2.x应用程序,你需要查看源代码3.2stable分支。这看起来像猴子补丁date_select

的地方