Change default Rails text_area helper rows/cols

六眼飞鱼酱① 提交于 2019-12-04 10:55:32

You can do:

  1. Write own helper:

    def readable_text_area(form, method, options = {}) form.text_area(method, options) end

  2. or redefine text_area method delegating to original text_area with proper options

  3. or extend ActionView::Helpers::InstanceTagMethods with your own method "my_text_area" and delegate to original text_area with proper options. Then you can use "f.my_text_area(...)"

  4. or change DEFAULT_TEXT_AREA_OPTIONS:

.

module ActionView::Helpers::InstanceTagMethods
  remove_const :DEFAULT_TEXT_AREA_OPTIONS
  DEFAULT_TEXT_AREA_OPTIONS = { "cols" => 40, "rows" => 5 }
end

Option 1 is most clean. 2 & 3 patch known public interface - seems acceptable. 4 patches internals - risky.

I'm a fan of:

class ActionView::Helpers::InstanceTag
  silence_warnings do
    DEFAULT_FIELD_OPTIONS = {}
    DEFAULT_TEXT_AREA_OPTIONS = {}
  end
end

As @gertas warned this is patching internals so it comes with risk. These constants have moved around in Rails occasionally. But overall it is not a huge deal. Either:

  1. You are using CSS for width and height so these attributes are being ignored anyway. In that case all you are doing is saving a few useless characters from moving across the screen. If it stops working you just spend a few extra characters until you notice it.
  2. You are using these attributes so when the hack stops working it becomes obvious (the field size changes) and you can fix it quickly.

So it does come with risk. But not much and it the most straight forward way to adjust these defaults.

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