Module: OnTheSpot::ControllerExtension::ClassMethods

Defined in:
lib/on_the_spot/controller_extension.rb

Overview

if this method is called inside a controller, the edit-on-the-spot controller action is added that will allow to edit fields in place

Instance Method Summary collapse

Instance Method Details

#can_edit_on_the_spot(options = {}) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/on_the_spot/controller_extension.rb', line 11

def can_edit_on_the_spot(options = {})
  define_method :update_attribute_on_the_spot do
    klass, field, id = params[:id].split('__')
    select_data = params[:select_array]
    object = klass.camelize.constantize.find(id)
    if options[:cancan]
      authorize!(options[:cancan], object)
    end
    if object.update_attributes(field => params[:value])
      if select_data.nil?
        render :text => CGI::escapeHTML(object.send(field).to_s)
      else
        parsed_data = JSON.parse(select_data.gsub("'", '"'))
        render :text => parsed_data[object.send(field).to_s]
      end
    else
      render :text => object.errors.full_messages.join("\n"), :status => 422
    end
  end
end