How to access a Ruby Module method
I have a Ruby module for constants. It has a list of variables and one metho开发者_如何学Pythond which applies formatting.
I can't seem to access the method in this module. Any idea why?
If you include the module the method becomes an instance method but if you extend the module then it becomes a class method.
module Const
  def format
    puts 'Done!'
  end
end
class Car
  include Const
end
Car.new.format # Done!
Car.format # NoMethodError: undefined method format for Car:Class
class Bus
  extend Const
end
Bus.format # Done!
Bus.new.format # NoMethodError: undefined method format
module Foo
  def self.hello # This is a class method
    puts "self.hello"
  end
  def hello # When you include this module, it becomes an instance method 
    puts "hello"
  end
end
Foo.hello #=> self.hello
class Bar
  include Foo
end
Bar.new.hello #=> hello
Generally, with modules, these things should be happening :
- Autoload path in application.rb, add: - config.autoload_paths += %W(#{config.root}/lib)
- Place module in /lib 
- Include module with - include NAMEOFMODULE
If the module name has an underscore like "game_engine", you need to use include GameEngine
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论