class AutoForme::Frameworks::Rails

  1. lib/autoforme/frameworks/rails.rb
Superclass: Framework

Methods

Public Class

  1. new
  2. setup

Public Instance

  1. setup_routes

Constants

ALL_SUPPORTED_ACTIONS_REGEXP = Regexp.union(AutoForme::Action::ALL_SUPPORTED_ACTIONS.map{|x| /#{Regexp.escape(x)}/})  

Public Class methods

new (*)

Define an autoforme method in the controller which handles the actions.

[show source]
# File lib/autoforme/frameworks/rails.rb, line 46
def initialize(*)
  super
  framework = self
  @controller.send(:define_method, :autoforme) do
    if @autoforme_action = framework.action_for(Request.new(self))
      if redirect = catch(:redirect){@autoforme_text = @autoforme_action.handle; nil}
        redirect_to redirect
      elsif @autoforme_action.output_type == 'csv'
        response.headers['Content-Type'] = 'text/csv'
        response.headers['Content-Disposition'] = "attachment; filename=#{@autoforme_action.output_filename}"
        render :body=>@autoforme_text
      elsif @autoforme_action.request.xhr?
        render :html=>@autoforme_text.html_safe
      else
        render :inline=>"<%=raw @autoforme_text %>", :layout=>true
      end
    else
      render :plain=>'Unhandled Request', :status=>404
    end
  end
end
setup (controller, opts, &block)

After setting up the framework, add a route for the framework to Rails, so that requests are correctly routed.

[show source]
# File lib/autoforme/frameworks/rails.rb, line 39
def self.setup(controller, opts, &block)
  f = super
  f.setup_routes
  f
end

Public Instance methods

setup_routes ()

Add a route for the framework to Rails routing.

[show source]
# File lib/autoforme/frameworks/rails.rb, line 71
def setup_routes
  if prefix
    pre = prefix.to_s[1..-1] + '/'
  end
  model_regexp = Regexp.union(models.keys.map{|m| Regexp.escape(m)})
  controller = @controller.name.sub(/Controller\z/, '').underscore
  ::Rails.application.routes.prepend do
    match "#{pre}:autoforme_model/:autoforme_action(/:id)" , :controller=>controller, :action=>'autoforme', :via=>[:get, :post],
      :constraints=>{:autoforme_model=>model_regexp, :autoforme_action=>ALL_SUPPORTED_ACTIONS_REGEXP}
  end
  ::Rails.application.reload_routes!
end