UrlHelperとAnother HTML-lint
RailsのUrlHelperはあまり好きじゃないという事を以前書いた。staticな記述を行うのに、Railsの機能を使って、ビュー(HTML)の領域に進出する必要は無いと考えているからだ。
だが、プロジェクトではヘルパを利用すべきというプロジェクトもあるので、今は使っているのだが、ヘルパを利用すると、Another HTML-lintでの得点が低くなってしまう事が多々ある。得点と書いたが、ユーザビリティという観点から見ても同じである。
例えば、button_toやlink_toではonclickは追加されるが、onkeypressは追加されないので、application_helper.rbあたりに以下を追加した。他のメソッドも沢山あるだろうが、こういったものがまとめられていると便利だと思う。
link_to
def link_to(name, options = {}, html_options = nil, *parameters_for_method_reference) if html_options html_options = html_options.stringify_keys convert_options_to_javascript!(html_options) html_options["onkeypress"] = html_options["onclick"] tag_options = tag_options(html_options) else tag_options = nil end url = options.is_a?(String) ? options : self.url_for(options, *parameters_for_method_reference) "<a href=\"#{url}\"#{tag_options}>#{name || url}</a>" end
button_to
def button_to(name, options = {}, html_options = {}) html_options = html_options.stringify_keys convert_boolean_attributes!(html_options, %w( disabled )) method_tag = '' if (method = html_options.delete('method')) && %w{put delete}.include?(method.to_s) method_tag = tag('input', :type => 'hidden', :name => '_method', :value => method.to_s) end form_method = method.to_s == 'get' ? 'get' : 'post' if confirm = html_options.delete("confirm") html_options["onclick"] = "return #{confirm_javascript_function(confirm)};" html_options["onkeypress"] = "return #{confirm_javascript_function(confirm)};" end url = options.is_a?(String) ? options : self.url_for(options) name ||= url html_options.merge!("type" => "submit", "value" => name) "<form method=\"#{form_method}\" action=\"#{escape_once url}\" class=\"button-to\"><div>" + method_tag + tag("input", html_options) + "</div></form>" end