Skip to content

Commit

Permalink
First pass using method_missing and OpenStruct.
Browse files Browse the repository at this point in the history
  • Loading branch information
whamilton42 committed Aug 8, 2013
1 parent d667f3d commit 4f4c8af
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
21 changes: 20 additions & 1 deletion lib/companies_house/response.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
require "active_support/core_ext/string/inflections"
require "ostruct"

module CompaniesHouse

class Response

attr_reader :attributes
attr_reader :attributes, :struct

def initialize(response)
check_for_errors(response)
Expand All @@ -26,6 +29,14 @@ def [](key)
@attributes[key]
end

def method_missing(sym, *args, &block)
if @struct.respond_to?(sym)
@struct.send(sym)
else
super sym, *args, &block
end
end

private

def check_for_errors(response)
Expand All @@ -44,9 +55,17 @@ def parse_response(response)
body = response.body.encode("UTF-8", "ISO-8859-1")
data = JSON.parse(body)
@attributes = data["primaryTopic"]
@struct = build_open_struct(@attributes)
rescue JSON::ParserError=> e
error_msg = "Companies house is having problems: #{response.body}"
raise ServerError.new(error_msg)
end

def build_open_struct(hash)
hash.each_with_object(OpenStruct.new) do |(key, value), struct|
value = build_open_struct(value) if value.is_a?(Hash)
struct.send("#{key.underscore}=", value)
end
end
end
end
3 changes: 2 additions & 1 deletion open_companies_house.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Gem::Specification.new do |gem|

gem.add_dependency "faraday", "~> 0.8.4"
gem.add_dependency "json"
gem.add_dependency "activesupport"

gem.name = 'open-companies-house'
gem.summary = "A wrapper around Companies House Open API"
Expand All @@ -17,4 +18,4 @@ Gem::Specification.new do |gem|
gem.require_paths = ['lib']
gem.files = `git ls-files`.split("\n")
gem.test_files = `git ls-files -- spec/*`.split("\n")
end
end
8 changes: 8 additions & 0 deletions spec/companies_house/response_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@
it "makes SIC code available as a convenience method" do
@response.sic_code.should == "62090"
end

it "makes attributes accessible as methods on the object body" do
@response.company_name.should == "GOCARDLESS LTD"
end

it "makes nested attributes accessible as chained methods on the object body" do
@response.reg_address.address_line1.should == "22-25 FINSBURY SQUARE"
end
end

context "with a company that doesn't exist" do
Expand Down

0 comments on commit 4f4c8af

Please sign in to comment.