Last active
December 21, 2015 00:19
-
-
Save kalpesh-fulpagare/6219482 to your computer and use it in GitHub Desktop.
Meta-programming Method to find the resource for controllers
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 ApplicationController < ActionController::Base | |
%w(user category post comment).each do |name| | |
define_method "find_#{name}" do | |
obj = instance_variable_set("@#{name}", name.camelize.constantize.find_by_id(params[:id])) | |
unless obj | |
flash[:alert] = "#{name.camelize} not found" | |
respond_to do |format| | |
format.html{ redirect_to "/#{name.pluralize}" } | |
format.js{ render js: "window.location='/#{name.pluralize}'" } | |
end | |
end | |
end | |
end | |
end | |
class UsersController < ApplicationController | |
before_action :find_user, only: [:show, :edit, :update, :destroy] | |
end | |
class CategoriesController < ApplicationController | |
before_action :find_category, only: [:show, :edit, :update, :destroy] | |
end | |
class PostsController < ApplicationController | |
before_action :find_post, only: [:show, :edit, :update, :destroy] | |
end | |
class CommentController < ApplicationController | |
before_action :find_Comment, only: [:show, :edit, :update, :destroy] | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment