Module: Cyrax::ControllerHelper

Defined in:
lib/cyrax/helpers/controller.rb

Instance Method Summary collapse

Instance Method Details

#respond_with(*args, &block) ⇒ Object



2
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
30
31
32
33
34
35
36
# File 'lib/cyrax/helpers/controller.rb', line 2

def respond_with(*args, &block)
  if args.present? && args.first.is_a?(Cyrax::Response)
    response, options = *args
    options = {
      notice: response.notice,
      error: response.error
    }.merge(options || {})

    # override status if needed
    options[:status] = response.status if response.status

    # convert result to model if possible
    result = response.result
    result = result.to_model if result.respond_to?(:to_model)

    respond_to do |format|
      format.any do
        # set flashes
        if response.success?
          flash[:notice] = options[:notice] if options[:notice].present?
        else
          flash.now[:notice] = options[:notice] if options[:notice].present?
          flash.now[:error] = options[:error] if options[:error].present?
        end
        set_resource_from(response)
        super(result, options, &block)
      end
      format.json do
        render json: response.as_json
      end
    end
  else
    super(*args)
  end
end

#set_resource_from(response) ⇒ Object



38
39
40
41
42
43
# File 'lib/cyrax/helpers/controller.rb', line 38

def set_resource_from(response)
  instance_variable_set("@#{response.resource_name}", response.result)
  response.assignments.each do |key, value|
    instance_variable_set("@#{key}", value)
  end if response.assignments.present? && response.assignments.is_a?(Hash)
end