Last active
December 15, 2015 11:29
-
-
Save sinsoku/5253376 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module RESTful | |
extend ActiveSupport::Concern | |
def resource_name | |
@resource_name ||= controller_name.singularize | |
end | |
def model_class | |
@model_class ||= resource_name.camelize.constantize | |
end | |
def param_sym | |
@param_sym ||= resource_name.to_sym | |
end | |
def index | |
instance_variable_set("@#{resource_name.pluralize}", model_class.scoped) | |
respond_with instance_variable_get("@#{resource_name.pluralize}") | |
end | |
def show | |
instance_variable_set("@#{resource_name}", model_class.where(id: params[:id]).first) | |
respond_with instance_variable_get("@#{resource_name}") | |
end | |
def create | |
instance_variable_set("@#{resource_name}", model_class.new(params[param_sym])) | |
flash[:notice] = "#{model_class.class_name} was successfully created." if instance_variable_get("@#{resource_name}").save | |
respond_with instance_variable_get("@#{resource_name}") | |
end | |
def update | |
instance_variable_set("@#{resource_name}", model_class.where(id: params[:id]).first) | |
flash[:notice] = "#{model_class.class_name} was successfully updated." if instance_variable_get("@#{resource_name}").update_attributes(params[param_sym]) | |
respond_with instance_variable_get("@#{resource_name}") | |
end | |
def destroy | |
instance_variable_set("@#{resource_name}", model_class.where(id: params[:id]).first) | |
flash[:notice] = "#{model_class.class_name} was successfully deleted." if instance_variable_get("@#{resource_name}").destroy | |
respond_with instance_variable_get("@#{resource_name}") | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UsersController < ApplicationController | |
include ::RESTful | |
respond_to :json | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment