Module: BetterController::ActionHelpers::ClassMethods

Defined in:
lib/better_controller/action_helpers.rb

Overview

Define standard CRUD actions for a resource

Instance Method Summary collapse

Instance Method Details

#standard_actions(resource_class, options = {}) ⇒ Object



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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/better_controller/action_helpers.rb', line 12

def standard_actions(resource_class, options = {})
  resource_name   = resource_class.name.underscore
  resource_name.pluralize

  # Define index action
  define_method(:index) do
    execute_action do
      collection = resource_class.all

      # Apply scopes if provided
      collection = apply_scopes(collection) if respond_to?(:apply_scopes)

      # Apply pagination if requested
      if options[:paginate]
        respond_with_pagination(collection, page: params[:page], per_page: params[:per_page])
      else
        respond_with_success(collection)
      end
    end
  end

  # Define show action
  define_method(:show) do
    execute_action do
      resource = resource_class.find(params[:id])
      respond_with_success(resource)
    end
  end

  # Define create action
  define_method(:create) do
    execute_action do
      resource = resource_class.new(send(:"#{resource_name}_params"))

      with_transaction do
        resource.save!
        respond_with_success(resource, status: :created)
      end
    end
  end

  # Define update action
  define_method(:update) do
    execute_action do
      resource = resource_class.find(params[:id])

      with_transaction do
        resource.update!(send(:"#{resource_name}_params"))
        respond_with_success(resource)
      end
    end
  end

  # Define destroy action
  define_method(:destroy) do
    execute_action do
      resource = resource_class.find(params[:id])
      resource.destroy
      respond_with_success(nil, status: :no_content)
    end
  end
end