Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby include module's single method in model

I have a module of following

module SimpleTask
    def task1
    end
    def task2
    end
    def task3
    end
end

And I have a model which requires only task2 method of module SimpleTask.

I know including SimpleTask in my model with include SimpleTask would do the job.

But I wonder if I can only include specific task2 method in my model.

like image 961
Gagan Avatar asked Jun 29 '11 04:06

Gagan


People also ask

How do you call a method inside a module in Ruby?

To access the instance method defined inside the module, the user has to include the module inside a class and then use the class instance to access that method.

How do you call a method in a module?

As with class methods, you call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.

Can modules include other modules Ruby?

Indeed, a module can be included in another module or class by using the include , prepend and extend keywords. Before to start this section, feel free to read my article about the Ruby Object Model if you're unfamiliar with the ancestor chain in Ruby.

Can Ruby modules have private methods?

You can only use private methods with:Other methods from the same class. Methods inherited from the parent class. Methods included from a module.


1 Answers

It sounds like you need to refactor #task2 into a separate module (e.g., BaseTask). Then you can easily include only BaseTask where you only need #task2.

module BaseTask
  def task2
    ...
  end
end

module SimpleTask
  include BaseTask

  def task1
    ...
  end

  def task3
    ...
  end
end

It's hard to help much more without a more concrete question (such as interdependence between the methods of SimpleTask, etc.

You could do some meta-programming where you include SimpleTask and then undefine the methods you don't want, but that's pretty ugly IMO.

like image 55
krohrbaugh Avatar answered Oct 16 '22 19:10

krohrbaugh