问题:
在Rails 4.2中,为textarea设置全局默认值
cols
和
rows
:
SimpleForm 3.0版
轨道4.2
科尔斯
排
价值观(参见
调试
以下是原因),然后我提出了以下解决方法:
解决方法1(测试工作):
# config/initializers/text_area_extensions.rb
module TextAreaExtensions
def render
@options[:cols] ||= 40
@options[:rows] ||= 20
super
end
end
ActionView::Helpers::Tags::TextArea.class_eval do
prepend TextAreaExtensions
end
... 将呈现任何文本区域(simpleform builder或rails form builder或text_area_tag)以具有以下默认列和行:
<textarea class="text" cols="40" rows="20"></textarea>
注意
ActionView::Helpers::Tags::TextArea
上课。以后的Rails主要版本甚至次要版本可能都不起作用!
而不是“修补”
ActionView::帮助程序::标记::文本区域
SimpleForm::Inputs::TextInput
解决方法3:
可能更好的方法是使用可以调用的自定义方法(即视图助手方法),该方法已经具有默认的列和行,而不是像上面的解决方案1那样“修补”gem代码。然而,我的印象是,您已经有了一个大型应用程序,您只需要设置一个全局代码,而不是手动设置/更新所有受影响的视图文件(您甚至在上面说过),因此我的解决方案1以上。
调试:
-
SimpleForm "text" input
:
module SimpleForm
module Inputs
class TextInput < Base
enable :placeholder, :maxlength
def input
@builder.text_area(attribute_name, input_html_options)
end
end
end
end
-
... 它不建议在SimpleForm中使用公共API来设置全局默认列和行,如下所示
input_html_options
:
# ...
@input_html_options = html_options_for(:input, input_html_classes).tap do |o|
o[:readonly] = true if has_readonly?
o[:disabled] = true if has_disabled?
o[:autofocus] = true if has_autofocus?
end
# ...
-
@builder.text_area
(见上面的代码),这让我
here
:
def text_area(object_name, method, options = {})
Tags::TextArea.new(object_name, method, self, options).render
end
-
here: for
TextArea.new
def initialize(object_name, method_name, template_object, options = {})
@object_name, @method_name = object_name.to_s.dup, method_name.to_s.dup
@template_object = template_object
@object_name.sub!(/\[\]$/,"") || @object_name.sub!(/\[\]\]$/,"]")
@object = retrieve_object(options.delete(:object))
@options = options
@auto_index = retrieve_autoindex(Regexp.last_match.pre_match) if Regexp.last_match
end
-
... 它也没有用于设置全局列和行的公共API,因此
next here: for
TextArea.new.render
def render
options = @options.stringify_keys
add_default_name_and_id(options)
if size = options.delete("size")
options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split)
end
content_tag("textarea", options.delete("value") { value_before_type_cast(object) }, options)
end
-
... 它也没有设置全局列和行的公共API,这让我别无选择,只能使用上面的解决方案1“修补”代码。
-
当你说Rails 4不再设置默认值时,我验证了你是对的
科尔斯
和
排
textarea
,因为看起来
DEFAULT_TEXT_AREA_OPTIONS = { "cols" => 40, "rows" => 20 }
here