29th
Use form_for from Rails’ console
As a curious developer, I always like to inspect an objects guts on the console, that way I can now as much as I can from the class without reading the documentation. It was the time for the rails form_for view helper. I had no idea how to access that from the terminal whatsoever, so I googled a bit and I found nice tidbits that got me going pretty quickly.
However when you try to use a method like form_for, a NoMethodError is being thrown because you are trying to call url_for for on a nil instance. This is because the default console helper doesn’t have any controller assigned. This can be easily fixed:
helper.controller = ActionController::Integration::Session.new
However, when we try again the form_for method we get a new error.
NoMethodError: undefined method `protect_against_forgery?' for #<ActionController::Integration::Session:0x10608a460>
It seems that for some reason, the ActionController integration session doesn’t support the forgery protection, because this is not a biggie for what we need we are just going to stub the method, and go our own way.
s = ActionController::Integration::Session.new
class << s; def protect_against_forgery?; false; end; end
helper.controller = ActionController::Integration::Session.new
At this point we thought we were going get away with it… well no, it seems it never stops.
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.<<
from /Users/roman/Sites/git/work/noomii/vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb:32:in `concat'
from /Users/roman/Sites/git/work/noomii/vendor/rails/actionpack/lib/action_view/helpers/form_helper.rb:281:in `form_for_without_haml'
from /Library/Ruby/Gems/1.8/gems/haml-2.2.9/lib/haml/helpers/action_view_mods.rb:170:in `form_for'
from (irb):16
The default helper object doesn’t have an initialized output buffer either!… luckily is easy to skip this one as well.
s = ActionController::Integration::Session.new
class << s; def protect_against_forgery?; false; end; end
helper.controller = ActionController::Integration::Session.new
helper.output_buffer = ''
f = nil
u = User.new
helper.form_for { |_f| f = _f }
f
>> #<Forms::ApplicationFormBuilder:0x105d7d330 @proc=#<Proc:0x0000000105d80648@(irb):16gt;
Oh the nice smell of victory!
