Bilal and Olga
Bilal and Olga

Reputation: 3251

Ruby mixin gives unidentified constant error

In irb, I do this

class Text
  include FileUtils
end

I get: NameError: uninitialized constant Test::FileUtils

If I just do: include FileUtils (i.e. now class) everthing works.

What gives?

Upvotes: 8

Views: 4687

Answers (3)

vikas027
vikas027

Reputation: 5762

This is an old thread, but still if any bumps on this thread to find an answer. One just needs to add below line on top of his code (or anywhere outside the class/method/module)

require 'fileutils'

Including in the class does not works, may be it used to work in older versions.

Upvotes: 1

Gareth
Gareth

Reputation: 138042

You need to make sure Ruby knows about the FileUtils module. That module isn't loaded by default:

>> FileUtils
NameError: uninitialized constant FileUtils
    from (irb):1
>> require 'fileutils'
=> true
>> FileUtils
=> FileUtils

Don't worry too much about the error NameError: uninitialized constant Text::FileUtils - when you try to include a constant that Ruby doesn't know about, it looks in a few places. In your case, first it will look for Text::FileUtils and then it will look for ::FileUtils in the root namespace. If it can't find it anywhere (which in your case it couldn't) then the error message will tell you the first place it looked.

Upvotes: 17

Randy Simon
Randy Simon

Reputation: 3324

Did you try?

class Text
  include ::FileUtils
end

This assumes that FileUtils is not within a module.

Upvotes: 1

Related Questions