0

I have included given code and its working fine

def check_ip
  start = IPAddr.new(10.10.0.10).to_i
  last = IPAddr.new(20.10.10.16).to_i        
  begin
    ip_pool = IpPool.pluck(:start_ip, :end_ip)
    # [["10.10.10.12", "10.10.10.15"], ["192.168.1.13", "192.168.1.13"]]
    low = IPAddr.new("10.10.10.12").to_i
    high = IPAddr.new("10.10.10.15").to_i     
    # it will check so on with ["192.168.1.13", "192.168.1.13"] values too       
    raise ArgumentError, I18n.t('errors.start')  if ((low..high)===start or (low..high)===last      
  end
  rescue ArgumentError => msg
    self.errors.add(:start, msg)
    return false
  end
  return true
end

Please guide me on how to implement this code without giving static value IPAddr.new("10.10.10.12").to_i I want to add values dynamically which I am fetching in ip_pool array so in low and high I am giving static values which are present in an array how could I give this values dynamically.

1 Answer 1

1

Since you have an array of low/high, you probably want to check all items in it:

begin
  IpPool.pluck(:start_ip, :end_ip).each do |(low,high)|
    raise ArgumentError, I18n.t('errors.start') \
      if (low..high) === start || (low..high) === last      
  end
  true
rescue ArgumentError => msg
  self.errors.add(:start, msg)
  false
end

Please note that I have the code a bit cleaned up:

  • removed superfluous returns;
  • corrected begin-rescue clause (there was a superfluous end right before rescue, that actually addressed rescue to the whole function body.
Sign up to request clarification or add additional context in comments.

2 Comments

but in this we are iterating it is there any solution that i will not iterate it because if there are thousands of record then it will iterate about thousand times
If you want to check against the only element in IpPool you might use IpPool.first or IpPool.detect { CONDITION } or IpPool.select { CONDITION } in place of IpPool.each, but your question means probably that I misunderstood your requirements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.