lib/rixml.rb in rixml-0.0.3 vs lib/rixml.rb in rixml-0.0.4
- old
+ new
@@ -7,27 +7,28 @@
def initialize(document)
@attrs = Hash.from_xml(document.to_s)
end
def product_id
- @attrs['Research']['Product']['productID']
+ deep_value('Research', 'Product', 'productID')
end
def status
- @attrs['Research']['Product']['StatusInfo']['statusType'].try(:downcase).try(:to_sym) || :published
+ deep_value('Research', 'Product', 'StatusInfo', 'statusType').try(:downcase).try(:to_sym) || :published
end
def publication_date
- DateTime.strptime(@attrs['Research']['Product']['StatusInfo']['statusDateTime'])
+ time_str = deep_value('Research', 'Product', 'StatusInfo', 'statusDateTime') || DateTime.now.to_s
+ DateTime.strptime(time_str)
end
def authors
- org = @attrs['Research']['Product']['Source']['Organization']
+ org = deep_value('Research', 'Product', 'Source', 'Organization') || {}
if org.is_a? Array
org = org.find { |v| v['primaryIndicator'] == 'Yes' } || org.first
end
- authors = org['PersonGroup']['PersonGroupMember']
+ authors = RIXML.deep_value(org, 'PersonGroup', 'PersonGroupMember') || []
authors = [authors] unless authors.is_a? Array
authors.map do |author|
person = author['Person']
{
@@ -40,21 +41,21 @@
}
end
end
def report_info
- content = @attrs['Research']['Product']['Content']
+ content = deep_value('Research', 'Product', 'Content')
{
title: content['Title'],
abstract: content['Abstract'],
- file_name: content['Resource']['Name'],
- pages: content['Resource']['Length'].to_i
+ file_name: content['Resource'].try(:[], 'Name'),
+ pages: content['Resource'].try(:[], 'Length').to_i
}
end
def context
- context = @attrs['Research']['Product']['Context']
+ context = deep_value('Research', 'Product', 'Context')
context_info = {
companies: RIXML.extract_companies_from_context(context),
sectors: RIXML.extract_sectors_from_context(context)
}
end
@@ -66,9 +67,17 @@
def self.parse_from_file filename
self.parse self.read_file(filename)
end
private
+
+ def self.deep_value(attrs, *keys)
+ keys.reduce(attrs) { |v, key| v.try(:[], key) }
+ end
+
+ def deep_value(*keys)
+ RIXML.deep_value(@attrs, *keys)
+ end
def self.read_file filename
body = ''
File.open(filename, 'r') do |infile|
while (line = infile.gets)