Ruby include module's single method in model

前端 未结 4 2281
难免孤独
难免孤独 2021-02-19 00:28

I have a module of following

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

And I have a model which r

4条回答
  •  清歌不尽
    2021-02-19 01:18

    You could add

    module SimpleTask
        def task1
        end
        def task2
        end
        def task3
        end
        module_function :task2
    end
    

    So that you can call the method like a class method on the module as well as having it as an instance method in the places you do want all three methods, ie:

    class Foo
       include SimpleTask
    end #=> Foo.new.task2
    class LessFoo
       def only_needs_the_one_method
          SimpleTask.task2
       end
    end #=> LessFoo.new.only_needs_the_one_method
    

    Or, if there's really no shared state in the module and you don't mind always using the module name itself, you can just declare all the methods class-level like so:

    module SimpleTask
        def self.task1
        end
        def self.task2
        end
        def self.task3
        end
    end
    
    class Foo
       include SimpleTask # Does, more or less nothing now
       def do_something
         SimpleTask.task1
       end
    end 
    #=> Foo.new.task2 #=> "task2 not a method or variable in Foo"
    #=> Foo.new.do_something does, however, work
    class LessFoo
       def only_needs_the_one_method
          SimpleTask.task2
       end
    end #=> LessFoo.new.only_needs_the_one_method works as well in this case
    

    But you'd have to change all the callers in that case.

提交回复
热议问题