开发者

Calling Ruby module methods from a nested class within

开发者 https://www.devze.com 2023-02-17 17:19 出处:网络
Is there an alternative to calling a Module method from a nested class? The code: module GroupSweeper def expire_cache(paths)

Is there an alternative to calling a Module method from a nested class? The code:

module GroupSweeper

  def expire_cache(paths)
    paths.each do |path|
      expire_page(path)
    end
  end

  class Sweeper开发者_开发百科One < ActionController::Caching::Sweeper
    include GroupSweeper
    observe Subject
    def after_save(subject)
      expire_cache([root_path,subjects_path])
    end
    def after_destroy(subject)
      expire_cache([root_path,subjects_path])
    end 
  end

end

How can I call GroupSweeper's expire_cache method from within SweeperOne without explicitely including it?

Thanks for any input.


You've got some circular dependencies going on here.

  • GroupSweeper defines a nested class of SweeperOne
  • SweeperOne includes GroupSweeper

That won't work.

To answer your ruby method/nested class question:

module MyModule
  def my_method
    puts "yo yo yo"
  end

  class MySweetClass
    def sweet_method
      puts "swweeeeeeeeeeeet"
    end
  end
end

And you want to call MySweetClass's sweet_method, you would change to be:

module MyModule
  def my_method
    puts "yo yo yo"
    MySweetClass.new.sweet_method
  end

  class MySweetClass
    def sweet_method
      puts "swweeeeeeeeeeeet"
    end
  end
end

#....

class MyClass
  include MyModule
end

MyClass.new.my_method

However! I think you're on the wrong track regarding rails' sweepers. This answer is very tactical, but I think you should open a question about what you're trying to do regarding rails sweepers.


I may be wrong as i'm pretty new to ruby myself, but the class should probably not include the module that it itself is part of.

maybe if you close the module with an end including it from the class should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消