How the View side is organized

I’ve always felt that the View side being compartimentalized in app/views/path/to/view.html.erb, app/helpers/path/to/view_helper.rb, app/assets/javascripts/path/to/view.js and app/assets/stylesheets/path/to/view.css, with the controller app/controllers/path/to_controller.rb.

For general site-wide JS and CSS that’s fine (a bit like there’s lib/ / gems to put general code), but I feel that it is putting closely related things very far from one another in the tree of documents of a Rails app. The fact that some files are in javascript and stylesheets is also redundant, we know that from the extension anyways.

I imagine they are currently organized this way because of how they get delivered, instead of how they are logically related. The fact that all CSS will typically be regrouped in a big file shouldn’t mean that they have to be grouped together to start with.

I feel that view.html.erb, view_helper.rb, view.js and view.css belong together and I wish that, by default, they would be (or at least could be) in the same folder. The controller could be one level higher too.

Thanks

1 Like

I think though that this would be at odds with the move away from sprockets and webpack.

I wonder if this ties in to https://discuss.rubyonrails.org/t/interactive-rails-new discussion.

If you are building a Rails app with extremely limited amounts of JavaScript this style of organization could work for you.

1 Like

@samsaffron could you by any chance elaborate on that?

Think grouping CSS / JS together with the markup would be a leaky structure as CSS and JS inherently have global state. It’d be really easy for CSS / JS in different controllers to clobber each other without any tooling enforcement.

1 Like

I think there is inherently something sensible about the approach you have suggested when designing and developing from a component based point of view.

It’s not a coincidence that most front end frameworks have some variation on this which at the end of the day allows you to say “this is a self contained search bar component” for example.

Outside of this I don’t see it as any kind of obvious improvement over what Rails offers currently.

However, there are ways of achieving this currently as you described. One way I’m currently playing around with is through using native web components where everything I need for a single component is by default grouped together and doesn’t leak CSS or JS outside of itself. I’d recommend playing around with it if you get a chance. I’m curious to hear others opinions on it!