ironsand ironsand - 6 months ago 13
Ruby Question

How to add a method to core class by gem

To add a method to core class I created a blank gem by:

bundle gem my_gem


Then edit a
.gemspec
and create a
lib/my_gem/core_ext/array.rb
file.

module MyGem::CoreExt::Array
def foo
p 'foo'
end
end

class Array
include MyGem::CoreExt::Array
end


Then I require the file from
lib/my_gem.rb
.

require 'my_gem/core_ext/array.rb'


And then by
bundle exec irb


> MyGem
=> MyGem
> [1,2,3].foo
NoMethodError: undefined method `foo' for [1, 2, 3]:Array
> MyGem::CoreExt::Array
NameError: uninitialized constant MyGem::CoreExt


I understand the file is not loaded, how can I load the file?

Answer

Your problem is how you're defining your module here: module MyGem::CoreExt::Array since you can't define MyGem::CoreExt::Array when MyGem::CoreExt doesn't exist.

my_gem/core_ext/array.rb

module MyGem
  module CoreExt
    module Array
      def foo
        p 'foo'
      end
    end
  end
end

Or, simply define MyGem::CoreExt before MyGem::CoreExt::Array:

module MyGem::CoreExt
end

module MyGem::CoreExt::Array
  def foo
    p 'foo'
  end
end

class Array
  include MyGem::CoreExt::Array
end

In IRB

require 'my_gem'

[].foo  # Should output 'foo'
Comments