Skip to content

Commit

Permalink
refactor json_rendering
Browse files Browse the repository at this point in the history
  • Loading branch information
msimonborg committed Jul 10, 2017
1 parent 1d8cd87 commit b5e76c7
Showing 1 changed file with 26 additions and 8 deletions.
34 changes: 26 additions & 8 deletions app/helpers/json_rendering.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down

0 comments on commit b5e76c7

Please sign in to comment.