user123
user123

Reputation: 163

how to fetch value from an array and check its range in rails

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.

Upvotes: 0

Views: 84

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

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.

Upvotes: 1

Related Questions