Skip to content

Instantly share code, notes, and snippets.

@kalpesh-fulpagare
Last active December 21, 2015 00:19
Show Gist options
  • Save kalpesh-fulpagare/6219482 to your computer and use it in GitHub Desktop.
Save kalpesh-fulpagare/6219482 to your computer and use it in GitHub Desktop.
Meta-programming Method to find the resource for controllers
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