Class: ActionController::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/auto_form.rb

Class Method Summary collapse

Class Method Details

.auto_form(model, method) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/auto_form.rb', line 3

def self.auto_form(model,method)
  action_name = "#{method}_#{model.name.underscore}"
  Rails.logger.info "\n\n\n#{action_name}"
  define_method(action_name) { |*args|
    form_erb = "<%= form_for(@params, :as => \"#{method}_args\", :url => { :action => params[:action] }) do |f| %>\
            <% @params.class.args.keys.each { |a| %>\
              <%= f.send(@params.class.args[a][:field_type],a) %><br/>\
            <% } %>\
            <%= f.submit \"Submit\" %>\
          <% end %>"
    args_class = model.const_get(method.to_s.camelize + "Args")
    if request.post?
      @params = args_class.new(params["#{method}_args"]) # compliant with ActiveModel API
      status, message = model.new.approve(@params)
      if status
        flash[:notice] = "#{model}##{method} successful"
        redirect_to '/'
      else
        flash.now[:error] = "#{model}##{method} failed: #{message.errors.first.join('-')}"
        render :layout => true, :inline => form_erb
      end
    else
      @params = args_class.new
      render :layout => true, :inline => form_erb
    end
  }
end