Write a Helper Extension
In Rails development, it comes often that you want to add/remove certain function that Rails pre-defined. For example, if you use Bootstrap 3, to have a form format correctly, each text_field needs to have class form-control. The best way to achieve that is to write a helper extension function and each time you have a text_field, it automatically adds the specified class for you.
First, we need to look at the helper definition (Reference: FormTagHelper). It tells us the actual function defined for text_field is:
def text_field(name, value = nil, options = {})
So in our extension module, we should use the same method, so it can maintain original functionality while adding more.
module BootstrapExtension
BOOTSTRAP_FORM_CLASS = "form-control"
def text_field(name, value = nil, options = {})
class_name = options[:class]
options[:class] = options[:class] || "#{FORM_CONTROL_CLASS}"
super
end
end
All it does is to define a class name for the text_field. If the field doesn't have any class associated, then use form-control class, but if there are, add form-control as additional one. The rest of method functionality is untouched.
Once you put that module inside application_helper.rb, you're all set.
module ApplicationHelper
module BootstrapExtension
...
...
end
include BootstrapExtension
end
There is another way of organizing the code. We could have a separate file for this BootstrapExtension module. Let's name it bootstrap_extension.rb. Then in application_helper.rb file, all we need to do is at the top of the file require our file and inside the ApplicationHelper module, include the module we defined in the file:
require 'bootstrap_extension'
module ApplicationHelper
include BootstrapExtension
end
It serves the exact purpose as the first option, but could keep application_helper.rb file cleaner if there are many additional modules defined.