hotwired / stimulus-rails

Use Stimulus in your Ruby on Rails app
https://stimulus.hotwired.dev
MIT License
638 stars 92 forks source link

Naming Convention not Matched #139

Closed SampsonCrowley closed 3 months ago

SampsonCrowley commented 4 months ago

https://stimulus.hotwired.dev/reference/controllers#naming-conventions

In filenames, separate multiple words using either underscores or dashes (snake_case or kebab-case: controllers/date_picker_controller.js, controllers/list-item-controller.js)

from the stimulus docs, I would think using the eagerLoadControllersFrom and lazyLoadControllersFrom would allow me to decide the conventions for my js controller file names

IMO kebab case is much less surprising in the mapping from filename to controller and better matches JS conventions (don't get me wrong, ruby files should be underscored, but I like kebab for JS)

but the code for eager and lazy load:

export function eagerLoadControllersFrom(under, application) {
  const paths = Object.keys(parseImportmapJson()).filter(path => path.match(new RegExp(`^${under}/.*_controller$`)))
  paths.forEach(path => registerControllerFromPath(path, under, application))
}

only matches underscored names (unless you mix and match which is the worst of both worlds)

I think there should be a very small update to change RegExp(^${under}/._controller$) to RegExp(^${under}/.[_-]controller$)

and in controllerFilename it should also parse the import map and return the first match

e.g.

function controllerFilename(name, under) {
  const reg = RegExp(`^${under}/${name.replace(/--/g, "/").replace("-", "[_-]"}[_-]controller`)
  return Object.keys(parseImportmapJson()).find(path => reg.test(path))
}
dhh commented 3 months ago

You don't have to use the JavaScript helpers provided for loading. You can certainly also do so by hand. But the point of a convention is to stick with one way of doing it by default, so that's what we're doing here.