How can I extend the gem class?

I wrote a gem with some basic logic that I wanted to share. I publish, install, use it.

There are additional features that, in my opinion, depend on my project. I want to add additional methods using the same class name because it is familiar and everything is easy for me to mentally track.

How can I set a gem and then add methods to it without conflict? In the past, I had rewritten methods defined in gems (especially Devise methods), but never tripped over the need to extend the class itself.

+4
source share
1 answer

You just open the class and add methods . If you know the name of the class and where it is located in the module hierarchy, then you simply create another file that defines the same class, and start adding methods. Since this is the same class name, methods will be added to another class.

This probably looks like what you did with Devise.

So, if I have a class Barin a gem, and it is inside a module namedFoo

# in the gem
module Foo
  class Bar
    def foobar
      'foobar!'
    end
  end
end

To add to this class a method called bazwithout changing the source code of gem, then in the application just create a new file, declare the class inside its module again and start adding material.

# in some other file in your app
module Foo
  class Bar
    def baz
      'foobar baz!'
    end
  end
end

 > f = Bar.new
 > f.foobar
=> 'foobar!'
 > f.baz
=> 'foobar baz!'

, .

baz Bar , Bar. , Bar, , Bar, .

class NewClass < Foo::Bar
  def baz
    'foobar baz!'
  end
end

 > nc = NewClass.new
 > nc.foobar
=> 'foobar!'
 > nc.baz
=> 'foobar baz!'
+6

Source: https://habr.com/ru/post/1539824/


All Articles