Xero
Xero

Reputation: 4173

Improve readability of object name in Rails

Context

Given that the convention for naming an object on Rails is like that :

/app/models/foo/bar.rb => class Foo::Bar

if I have a folder structure :

/app/models/foo/bar/object1.rb
/app/models/foo/bar/object2.rb
/app/models/foo/main.rb

To call this objects from my main, I have to do :

class Foo::Main

  def some_method
    Foo::Bar::Object1.new
    Foo::Bar::Object2.new
  end

end

This work fine. But here my question :

Question

Is there a way to improve the readability of the name of object ?

Given that in my Foo::Main is in the same namespace Foo; Is there a way to call them (Foo::Bar::Object1.new and Foo::Bar::Object2.new) with a shorter name ?

I would like to name them Bar::Object1.new and Bar::Object2.new, in this context (or Object1.new and Object2.new)

Expected

class Foo::Main

  def some_method
    Bar::Object1.new
    Bar::Object2.new
  end

end

This code is an exemple of what I'm expected, but it don't work.

Upvotes: 2

Views: 219

Answers (2)

Sebastian Scholl
Sebastian Scholl

Reputation: 1105

if you're interested in learning more about best practices on syntax I'd suggest using a tool like Rubocop: https://github.com/rubocop-hq/rubocop

Whether you end up making it apart of your workflow or not doesn't really matter. That said, it is hugely helpful in identifying best practices to improve your codes maintainability/readability and helps a lot when working on teams.

Upvotes: 0

mrzasa
mrzasa

Reputation: 23327

If you want to use the top module, you need to use nesting without the A::B shorthand:

module Foo
  class Main

    def some_method
      Bar::Object1.new
      Bar::Object2.new
    end
  end
end

Sources:

Upvotes: 7

Related Questions