Refactoring instance variables to local variables in Rails controllers
I like to use as much as possible the new features in Ruby. In this case, I will show how to take advantage of shorthand hash syntax whileThe on changing from instance variables to local variables in controllers and views.
Initial code
Say you have t...
allaboutcoding.ghinda.com9 min read
I really like the idea in the post! For some time already I feel that passing data between the controller and the view by setting an instance variable is one of the biggest and most fundamental design flaws of Rails – and I think you provide great examples of how to avoid it.
However, personally I'm not so sure about this keeping the controller action as a one-line render-only thing. Controllers are procedural in nature and I actually like to see what is happening in a step-by-step way. I can understand the allure of hiding the complexity of filtering books in a private method, but honestly I would prefer to at least set the user directly:
def index user = User.find(params[:user_id]) books = get_filtered_books render locals: { user:, books: } endI wonder what is your take on that.