Instance variables vs methods. When to use each? #360
-
I've been using ViewComponent for a while now and just now I realized I can define instance methods that are available to my view just like instance variables. I'm confused because I don't know wether I should always use one or the other or even a mix of both. As an example I have an class OnboardingChecklistComponent < ViewComponent::Base
def initialize(user:)
@user = user
@work_preference = user.work_preference
end
def work_preference_state
state_for(work_preference) # lets assume state can be :empty, :incomplete, :complete
end I then call in render Seeker::ChecklistItemComponent.new(state: work_preference_state, label: 'Your working preferences', path: edit_work_preference_path) In this example, I definitely won't be using My concrete questions with this example (which in real life is far more complex) are:
My take on this: It's a bit confusing that we can do both. In typical rails fashion, the only things available to the view are instance variables set on the controller. PROs: CONs: My guess is there should be a convention around this or probably even a top level decision to not allow instance methods to be used in views. What do you think? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
@pinzonjulian generally, I think both are fine! For simply making a value passed into the component initializer available in the template, instance variables are simple and lightweight. But it's often nice to write instance methods on component classes to express a certain behavior, such as changing the text of a label, in a Ruby method. We use both in our components at GitHub, generally in this fashion. |
Beta Was this translation helpful? Give feedback.
@pinzonjulian thank you for providing the detailed examples here. Some thoughts:
ViewComponent templates are compiled into instance methods on the component Ruby file. In that regard, the component and the template are the same entity. I have it on my to-do list to write up an explanation of this concept as part of the README, but here's an example: