Skip to content

Instantly share code, notes, and snippets.

@benoitr
Created March 7, 2015 17:24
Show Gist options
  • Save benoitr/be77908cf9012d2195ba to your computer and use it in GitHub Desktop.
Save benoitr/be77908cf9012d2195ba to your computer and use it in GitHub Desktop.
resource_controller
class Admin::ResourceController < Admin::BaseController
before_action :load_resource
def index
respond_with @collection
end
def edit
respond_with(:admin, @object)
end
def new
respond_with(:admin, @object)
end
def update
@object.update(permitted_resource_params)
respond_with(:admin, @object)
end
def create
@object.attributes = permitted_resource_params
respond_with(:admin, @object)
end
def model_class
controller_name.classify.constantize
end
def object_name
controller_name.singularize
end
def load_resource
if member_action?
@object ||= load_resource_instance
instance_variable_set("@#{object_name}", @object)
else
@collection ||= collection
instance_variable_set("@#{controller_name}", @collection)
end
end
def load_resource_instance
if new_actions.include?(action)
build_resource
elsif params[:id]
find_resource
end
end
def find_resource
model_class.find(params[:id])
end
def build_resource
model_class.new
end
def collection
model_class.all
end
def permitted_resource_params
params.require(object_name).permit!
end
def collection_actions
[:index]
end
def member_action?
!collection_actions.include? action
end
def new_actions
[:new, :create]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment