I have a ‘widget’ that comprises an html/css block of code. It is a type of data layout, which I call the ‘stack’.
The stack has bits of .erb (Ruby on Rails) embedded in it, which enters the data for each user.
I need to include this stack in multiple places, where it needs to represent different data from different models.
So, one stack might contain a field called @company.name and the other stack might contain @project.name || "Unidentified Project".
How does one refactor / organize this situation? Options that I can see:
- Have two separate
stacks, which would introduce redundancy and inconsistency, but would be an obvious answer to the problem without limit to scenario-specific customization. - Include
ifstatements for every data point to test which circumstance the stack is being used for, but this is very code-ugly and unsustainably complicated for more than 2 stacks. - Some unknown unknown.
How would you tackle this?
One simple way would be to write the erb in a generic way so that it works for either a project or a company for example, in your Project model you could put:
Then in your Company model put:
When you render the ERB, pass in a variable with some generic name like
main_objectand call itsdisplay_namefunction. The ERB code would not know or care what classmain_objectis:If it bothers you to put display-related functions like
display_namein your models, you could use the Presenter pattern. A present is basically a plain-old ruby object that you create from your model(s) and then pass to the view. I saw a good talk on this pattern by Jeff Casimir called “Fat Models Aren’t Enough” and the slides are here:http://en.oreilly.com/rails2011/public/schedule/detail/18514