Nested classes versus compact in Ruby -
working on initial rails project, , using rubocop analyze code style. led me question how ruby's nested classes work in context of rails. example, in engine, have model:
# app/models/app_core/tenant.rb module appcore class tenant < activerecord::base end end
and controller:
# app/controllers/app_core/tenant/members_controller.rb module appcore class tenant::memberscontroller < applicationcontroller end end
in model's case, module same path , class name same file name. in controllers case, sec part of path, "tenant" part of class name.
rubocop tells me should "use nested class definitions instead of compact style" in tenant::memberscontroller
line, if understand correctly...
module appcore class tenant class memberscontroller < applicationcontroller end end end
...this shouldn't create difference.
now, question have appcore::tenant model, appcore::tenant looks reopened , memberscontroller class added nested class. mean tenant class have nested class in it? need name models , controller routes differently? totally fine , nil worry about? not sure means.
one subtle difference scope different, , can cause errors. in first case constants looked in appcore
, whereas in sec case constants looked in appcore::tenant
. if qualify constant names doesn't create difference.
foo = :problem module foo = 42 # looks a::foo because of lexical scope module b def self.foo foo end end end # looks ::foo because of lexical scope module a::c def self.foo foo end end # looks a::foo, qualified ... ok technically ::a::foo qualified, meh. module a::d def self.foo a::foo end end a::b.foo # => 42 a::c.foo # => :problem a::d.foo # => 42
if referring constants defined in appcore::tenant
within memberscontroller
might create difference you. subtle perchance important, , aware of. i've nail in real life when had util
module string
submodule. moved method util
, broke because string
within method referred util::string
. changed naming conventions after that.
your tenant
module have memberscontroller
nested class. anywhere else in codebase can refer appcore::tenant::memberscontroller
. if want improve separation should name model classes differently, or set them within module such appcore::model
or similar. if you're using rails you'll have buck conventions, configuration required not bad.
ruby-on-rails ruby rubocop
No comments:
Post a Comment