ruby mixins errors
I'm confused with the following piece of code.
HTTParty library has class method named def self.get(..)
.
I include it in the Client
module and then include that Client
module in my Line
class and access the get
method in my def self.hi()
method.
But when I run, it throws out the error:
ruby geek-module.rb
geek-module.rb:12:in `hi': undefined method `get' for Line:Class (NoMethodError)
fro开发者_StackOverflow中文版m geek-module.rb:16:in `<main>'
Why I'm not being able to access that get
method of HTTParty?
Following is the code:
require 'rubygems'
require 'httparty'
module Client
include HTTParty
end
class Line
include Client
def self.hi
get("http://gogle.com")
end
end
puts Line.hi
You cannot access self.get method because you use include HTTParty
, include makes methods acessible by instances of class not class himself, your hi
method is class method but get
method is the instance method. If you use something like:
class Line
include Client
def hi
get("http://gogle.com")
end
end
line = Line.new
line.get
I think it should work
... or just use extend Client
rather than include
So, when you include HTTParty
in the Client
module you can access the get
method through Client.get
. And when you include Client
in the Line
class you can access the get
method through Client.get
too. Actually, if you want to use the get
method in your Line class, you don't need to include it. So:
require 'rubygems'
require 'httparty'
module Client
include HTTParty
end
class Line
def self.hi
Client.get("http://google.com")
end
end
puts Line.hi
or if you want the get
method in your Line
class you can use something like that:
class Client
include HTTParty
end
class Line < Client
def self.hi
get("http://google.com")
end
end
puts Line.hi
精彩评论