Last active
February 5, 2020 01:45
-
-
Save Mk-Etlinger/4191380da918daa8fce2f14b0395b05c to your computer and use it in GitHub Desktop.
Cleaned up meta programming set_resorcery method
This file contains hidden or 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::API | |
def metaprogram_controller_instance_variable | |
model_name = params['controller'].singularize | |
Model = Object.const_get(model_name.capitalize) | |
value_to_set = Model.find_by(id: params[:id]) | |
instance_variable_set('@' + model_name, value_to_set) | |
end | |
end | |
// Hello there! | |
// This snippet is something that I'm proud of but is about 2 years old by now | |
// It reminds me how magical and exciting programming can be. | |
// The snippet allows any Controller inside the Rails MVC architecture to | |
// access an instance variable with the same name as the controller itself. | |
// The Rails convention usually goes like '@recipe = Recipe.find_by(id: params[:id])' | |
// This abstracts that away for better or for worse(probably worse). | |
// Would love to talk through why I love this snippet, but we can leave that for our conversation. | |
// **Note This should absolutely never be used in a production environment | |
// Also, I left comments out in favor of naming things accurately and idiomatically | |
// Thanks for reading! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment