write a function that injects a class level function in Ruby

2283 views ruby
-2

I find myself writing the same function over and over in a bunch of my classes, is there a way to declare a function once, and then in each of the classes that I want to have that function, just reference the external function declaration and 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

# output should be "hello world"

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

Thanks, Kevin

answered question

1 Answer

8

You can do that using module.

For example:

module SomeModule
  def foo
    true
  end
end

class SomeClass
  include SomeModule
end

SomeClass.new.foo

posted this

Have an answer?

JD

Please login first before posting an answer.