The Crystal Programming Language Forum

How to avoid having to preface class with module name

For instance in testing, my spec.cr file might have

describe "Foo" do
  it "foos" do 
    bar = Bar.new(1)
    bar.baz.should eq(1)
  end
end

with the src file foo.cr including

module Foo 
  class Bar
    @baz : Int32
    
    def initialize(@baz)
    end

  end
end

This doesn’t work. I have to change the call in the spec file to

  bar = Foo::Bar.new(1)

This is a result of name spacing your type (which is a good practice). Although I wouldn’t recommend it, the way around it would be to include Foo within the top level. This would add all the types within Foo to the top level namespace.

A better solution would be some sort of import system like ES6. If/until that happens I would just continue using the FQN of your type.

1 Like

You can actually do:

module Foo
  describe Bar do
    it "..." do
      Bar.new
    end
  end
end

but I don’t know what do think about that…

Then, we could maybe introduce private include, which will add those types just to the file.

1 Like

private include or special semantics for top-level includes sound good to me.

1 Like

I think I would rather have an ES6 Import system. However that is probably not trivial…

Priviate includes would be more of a bandaid on the fact that the only way to avoid long type names is to include ALL the types of a namepsace into another, or define an alias.