From b5e76c7cf8752f5fa6cf0f53061621c8fb83c19e Mon Sep 17 00:00:00 2001 From: "M. Simon Borg" Date: Mon, 10 Jul 2017 10:43:23 -0400 Subject: [PATCH] refactor json_rendering --- app/helpers/json_rendering.rb | 34 ++++++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/app/helpers/json_rendering.rb b/app/helpers/json_rendering.rb index 8c0a3f62..3e3fa446 100644 --- a/app/helpers/json_rendering.rb +++ b/app/helpers/json_rendering.rb @@ -12,6 +12,16 @@ def initialize(json, options = {}) @route_prefix += '_' unless @route_prefix.end_with?('_') || @route_prefix.blank? end + %i[rep_url state_url district_url office_location_url].each do |method_name| + define_method(method_name) do |id| + if route_prefix.blank? + super(id) + else + send("#{route_prefix}#{method_name}", id) + end + end + end + def response(symbol, object) send(symbol, object) end @@ -29,29 +39,37 @@ def office_locations(office_locations) end def rep(rep) - return json.error 'Record not found' if rep.blank? - json.self send("#{route_prefix}rep_url", rep.official_id) - json.state { state rep.state } - json.district { district rep.district } if rep.district + return not_found if rep.blank? + json.self rep_url(rep.official_id) + state_and_district_for_rep(rep) _rep rep json.set! 'office_locations', rep.active_office_locations do |office_location| self.office_location office_location end end + def state_and_district_for_rep(rep) + json.state { state rep.state } + json.district { district rep.district } if rep.district + end + + def not_found + json.error 'Record not found' + end + def state(state) - json.self send("#{route_prefix}state_url", state.state_code) + json.self state_url(state.state_code) json.extract! state, :state_code, :name, :abbr end def district(district) - json.self send("#{route_prefix}district_url", district.full_code) + json.self district_url(district.full_code) json.extract! district, :full_code, :code, :state_code, :level, :chamber, :name end def office_location(office_location) - json.self send("#{route_prefix}office_location_url", office_location.office_id) - json.rep send("#{route_prefix}rep_url", office_location.official_id) + json.self office_location_url(office_location.office_id) + json.rep rep_url(office_location.official_id) json.extract! office_location, :active, :official_id, :level, :office_id, :bioguide_id, :state_leg_id, :office_type, :distance, :building, :address, :suite, :city, :state, :zip, :phone, :fax, :hours,