Instance variables vs methods. When to use each? #360
Unanswered
pinzonjulian
asked this question in
General
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.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
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
OnboardingChecklistComponent
which shows aChecklistItemComponent
, per item.I then call in
onboarding_checklist_component.html.erb
the reference to another component with some of the "calculations" I performed here.In this example, I definitely won't be using
@work_preference
in my view but I need it to calculate the state of the work preference progress. In my view I do need the state.My concrete questions with this example (which in real life is far more complex) are:
@work_preference
, which is not used in the view, be set as an instance variable or as an instance method?work_preference_state
, which IS used in the view, be set as an instance variable or a an instance method?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.
There are pros and cons though.
PROs:
I see great value in being able to declare methods of my component instance and use it in my instance's view. Specially for boolean methods that allow me to use question marks at the end (something I can't do with instance variables).
CONs:
This can lead to the view performing logic which should have been declared in the ruby file.
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.
All reactions