1require 'nokogiri'
 
2
 
3class Constituency < ActiveRecord::Base
 
4  class ApiQuery
 
5    CONSTITUENCIES    = '//Constituencies/Constituency'
 
6    CONSTITUENCY_ID   = './Constituency_Id'
 
7    CONSTITUENCY_NAME = './Name'
 
8    CONSTITUENCY_CODE = './ONSCode'
 
 9
 
10    CURRENT_MP = './RepresentingMembers/RepresentingMember[1]'
 
11    MP_ID      = './Member_Id'
 
12    MP_NAME    = './Member'
 
13    MP_START   = './StartDate'
 
14    MP_END     = './EndDate'
 
 
16    def fetch(postcode)
 
17      response = client.call(postcode)
 
 
19      if response.success?
 
20        parse(response.body)
 
21      else
 
22        []
 
23      end
 
24    rescue Faraday::ResourceNotFound, Faraday::ClientError => e
 
25      return []
 
26    rescue Faraday::Error => e
 
27      Appsignal.send_exception(e)
 
28      return []
 
29    end
 
 
31    def self.before_remove_const
 
32      Thread.current[:__api_client__] = nil
 
33    end
 
 
35    private
 
 
37    def client
 
38      Thread.current[:__api_client__] ||= ApiClient.new
 
39    end
 
 
41    def parse(body)
 
42      xml = Nokogiri::XML(body)
 
 
44      xml.xpath(CONSTITUENCIES).map do |node|
 
45        {}.tap do |attrs|
 
46          attrs[:name]        = node.xpath(CONSTITUENCY_NAME).text
 
47          attrs[:external_id] = node.xpath(CONSTITUENCY_ID).text
 
48          attrs[:ons_code]    = node.xpath(CONSTITUENCY_CODE).text
 
  • Found = in conditional. It should probably be an == » roodi
50          if mp = node.at_xpath(CURRENT_MP)
 
51            if mp.at_xpath(MP_END).text.present?
 
52              attrs.merge!(mp_id: nil, mp_name: nil, mp_date: nil)
 
53            else
 
54              attrs[:mp_id] = mp.xpath(MP_ID).text
 
55              attrs[:mp_name] = mp.xpath(MP_NAME).text
 
56              attrs[:mp_date] = mp.xpath(MP_START).text
 
57            end
 
58          end
 
59        end
 
60      end
 
61    end
 
62  end
 
63end