Friday 15 August 2008

secure forms

One thing I struggled with in RoR was creating forms that submitted to https. So I ended up writing a couple of helpers:

  def secure_form_for(record_or_name_or_array, *args, &proc)
unless RAILS_ENV == 'production'
url_options = {}
else
url_options = {:protocol => 'https://', :only_path => false }
end

options = args.last.is_a?(Hash) ? args.pop : {}
if !options[:url].nil?
options[:url] = url_options.merge options[:url]
else
options[:url] = url_options
end

return form_for(record_or_name_or_array, options, &proc)
end


and

  def secure_form_tag(*args, &proc)
logger.debug("secure_form_tag args #{args.inspect}")
unless RAILS_ENV == 'production'
url_options = {}
else
url_options = {:protocol => 'https://', :only_path => false }
end

options = args.last.is_a?(Hash) ? args.pop : {}
if !options[:url].nil?
options[:url] = url_options.merge options[:url]
else
options[:url] = url_options
end

logger.debug("secure_form_tag options #{options.inspect}")

return form_tag(options, &proc)
end


The should be simple replacements for form_for and form_tag. Now, I have to admit I wrote these when I was using Rails 1.2.5, so there might be some things in 2.x that make these redundant, but, they work for me.
The only caveat is that if you are doing a form where you are not passing in the action, just the object e.g

<% form_for @object do %>


Then you are going to have to supply the actions. I am looking into this now, and I might rewrite this post if I sort it out!

No comments: