Re: Form responders

Michael Houghton
2005-10-05T05:05:15Z

On 5 Oct 2005, at 02:48, Julian ''Julik'' Tarkhanov wrote:

> Odd question but I think it slips through without me noticing a viable
> response.
>
> How can I set up some meaningful ActiveRecord stub so that I can make
> a "form responder" - or even better, make my controller be this
> responder. What I would love to have is form values persisting through
> reloads without loading them manually into the view.
> Helpers nicely address this, but there the params are stored inside a
> model objects. Form helpers, as I take it, (by the way of the dirtiest
> hack on earth :-) can only address controller instance variables. So
> the question is - if I want to merely persist some values through
> reloads and use the form helpers (they are times more convenient than
> usual forms) the only way I can go about it is build a custom
> container class that will mimick AR::Base?

This isn''t too difficult, actually.

I have a SearchQuery object, that I build in just the way you describe.
It is a subclass of a truly noddy non-AR model, subclassed from a hash,
that I''ve included below. I''m sure it''s similar to
the code you wrote
for your Finder object, but if not I hope it''s of interest.

Stick this basic model in lib/simple_model.rb, make sure it is included
by require_dependency in something like application.rb, and subclass it
as needed.

Subclasses of this can be used to accept form parameters using the
normal

	@foo = Foo.new(params[:foo])

and will then persist the stuff as a model object in a way that is
meaningful for use with form helpers, just as if it was an AR base
model. I currently don''t do anything with these to store them, but
I''m
pretty sure they''d squirrel away fine in a session.

This is working pretty well for me - if anyone has any subtle
enhancements to it, I''d be interested to hear.

	Mike

-----

class SimpleModel < Hash

   Dependencies.remove_subclasses_for(SimpleModel) if
defined?(SimpleModel)

   # initialize - merges in the parameters passed
   def initialize(hash=nil)
     self.merge!(hash) if hash
   end

   def logger
     RAILS_DEFAULT_LOGGER
   end

   # method missing - simple map to hash key with same name
   def method_missing(method, *args)
     method = method.to_s
	# assignments, :foo     if method =~ /^(.*)=$/
       self[$1] = (args.length > 1 ? args : args.first)
	# accesses, :foo
     else
       self[method]
     end
   end

end