Skip to content

Instantly share code, notes, and snippets.

@Mk-Etlinger
Last active February 5, 2020 01:45
Show Gist options
  • Save Mk-Etlinger/4191380da918daa8fce2f14b0395b05c to your computer and use it in GitHub Desktop.
Save Mk-Etlinger/4191380da918daa8fce2f14b0395b05c to your computer and use it in GitHub Desktop.
Cleaned up meta programming set_resorcery method
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