Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

problems subclassing ip #23

Open
Canx opened this issue Nov 6, 2016 · 2 comments
Open

problems subclassing ip #23

Canx opened this issue Nov 6, 2016 · 2 comments

Comments

@Canx
Copy link

Canx commented Nov 6, 2016

Hi,

thanks for sharing this great library!

I'm trying to inherit from IP but I've got problems with the constructor:

$ ruby ip_extended.rb 
/var/lib/gems/2.3.0/gems/ruby-ip-0.9.3/lib/ip/base.rb:22:in `new': wrong number of arguments (given 3, expected 1) (ArgumentError)
        from ip_extended.rb:9:in `<main>'

The code:

require 'ip'

class IPExtended < IP
  def initialize(ip, param2, param3)
    super(ip)
  end
end

ip = IPExtended.new("192.168.1.1", true, true)
puts ip.to_s

I don't know what I'm doing wrong, could you help me please?

@candlerb
Copy link
Contributor

candlerb commented Nov 6, 2016

You'll have to be careful trying to do this. "IP.new" is overridden, so that it actually creates and returns an instance of IP::V4 or IP::V6 depending on the arguments given. It wasn't really designed to be extended the way you're trying.

@Canx
Copy link
Author

Canx commented Nov 7, 2016

Ok, I understand...

finally I used method_missing to extend the class:

require 'ip'

class IPExtended
  def initialize(ip, param2, param3)
    @ip = IP.new(ip)
    @param2 = param2
    @param3 = param3
  end

  # extended methods...

  def method_missing(method, *args, &block)
    @ip.send(method, *args, &block)
  end

end

ip = IPExtended.new("192.168.1.1", true, true)
puts ip.to_s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants