diff --git a/lib/user_agent_parser/device.rb b/lib/user_agent_parser/device.rb index bb1a9d2..0c5d0ec 100644 --- a/lib/user_agent_parser/device.rb +++ b/lib/user_agent_parser/device.rb @@ -25,5 +25,13 @@ def eql?(other) end alias == eql? + + def to_h + { + family: family, + model: model, + brand: brand + } + end end end diff --git a/lib/user_agent_parser/operating_system.rb b/lib/user_agent_parser/operating_system.rb index ee1f9d3..9eeea87 100644 --- a/lib/user_agent_parser/operating_system.rb +++ b/lib/user_agent_parser/operating_system.rb @@ -30,5 +30,12 @@ def eql?(other) end alias == eql? + + def to_h + { + version: version.to_h, + family: family + } + end end end diff --git a/lib/user_agent_parser/user_agent.rb b/lib/user_agent_parser/user_agent.rb index 65c7f30..ff9df9a 100644 --- a/lib/user_agent_parser/user_agent.rb +++ b/lib/user_agent_parser/user_agent.rb @@ -34,5 +34,14 @@ def eql?(other) end alias == eql? + + def to_h + { + device: device.to_h, + family: family, + os: os.to_h, + version: version.to_h + } + end end end diff --git a/lib/user_agent_parser/version.rb b/lib/user_agent_parser/version.rb index f6c3093..5555881 100644 --- a/lib/user_agent_parser/version.rb +++ b/lib/user_agent_parser/version.rb @@ -50,5 +50,15 @@ def eql?(other) def segments @segments ||= version.scan(SEGMENTS_REGEX) end + + def to_h + { + version: version, + major: major, + minor: minor, + patch: patch, + patch_minor: patch_minor + } + end end end diff --git a/spec/user_agent_spec.rb b/spec/user_agent_spec.rb index 4c78190..eaf8dd3 100644 --- a/spec/user_agent_spec.rb +++ b/spec/user_agent_spec.rb @@ -156,4 +156,18 @@ agent.inspect.must_equal '#' end end + + describe '#to_h' do + it 'returns everything' do + browser_version = UserAgentParser::Version.new('5.0.2') + os_version = UserAgentParser::Version.new('4.2.1') + os = UserAgentParser::OperatingSystem.new('iOS', os_version) + device = UserAgentParser::Device.new('iPhone') + agent = UserAgentParser::UserAgent.new('Mobile Safari', browser_version, os, device) + assert_equal( + {:device=>{:family=>"iPhone", :model=>"iPhone", :brand=>nil}, :family=>"Mobile Safari", :os=>{:version=>{:version=>"4.2.1", :major=>"4", :minor=>"2", :patch=>"1", :patch_minor=>nil}, :family=>"iOS"}, :version=>{:version=>"5.0.2", :major=>"5", :minor=>"0", :patch=>"2", :patch_minor=>nil}}, + agent.to_h + ) + end + end end