0

I write the same function repeatedly in my classes. Is there a way to declare a function once, and just reference the function declaration in each relevant class to have it become part of the class? I want to do something like:

def add_func
  expand self.new_func
    puts "hello"
  end
end

class A
  import "add_func"
end

A.new_func
# >> hello world

I'm looking to make a class method, not an instance method, but I'd be interested in knowing how to do both. What is the Ruby construct I am looking for?

sawa
  • 165,429
  • 45
  • 277
  • 381
user1130176
  • 1,772
  • 1
  • 23
  • 33

2 Answers2

3

You can extend the methods like this:

module SomeModule
  def foo
    true
  end
end

class SomeClass
  extend SomeModule
end

SomeClass.foo
  • 1
    This is almost right, def foo instead of def self.foo is what extends the class, please confirm – user1130176 Nov 04 '18 at 20:51
  • 2
    You can just `extend SomeModule` instead of `include SomeModule` and remove the `included` callback. – Stefan Nov 05 '18 at 10:04
  • 2
    What @Stefan said because right now `foo` is added as an instance method and again as a class instance method. e.g. `SomeClass.foo == SomeClass.new.foo` in this case I guess that works but in most real world cases extend and include serve very different purposes – engineersmnky Nov 05 '18 at 14:20
0

You cann package individual methods into their own modules and extend them:

module MyModule
  module NewFunc
    def new_func
      puts "hello"
    end
  end
end

class A
  extend MyModule::NewFunc
end

A.new_func

With some metaprogramming / monkeypatching you could make a way to extend only certain methods of a module, but I think the approach I have shown works good enough.

If you wanted to make it so individual methods can be imported, or you can import all of them, you can do it like so:

module MyModule
  module NewFunc
    def new_func
      puts "hello"
    end
  end

  module NewFunc2
    def new_func2
      puts "hello2"
    end
  end

  include NewFunc, NewFunc2 # this adds them to MyModule directly
end

class A
  extend MyModule
end

A.new_func
A.new_func2
max pleaner
  • 26,189
  • 9
  • 66
  • 118