yhirose / maxminddb

Pure Ruby GeoIP2 MaxMind DB reader.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Use value objects for responses

iGEL opened this issue · comments

I would prefer if you return not hashes, but value objects. One example how this could look like would be:

ret = db.lookup('74.125.225.224')
ret.class # => MaxMindDB::Result
ret.country.class # => MaxMindDB::Result::Country
ret.country.name # => 'Germany'
ret.country.name(:de) # => 'Deutschland'

It's probably just a wrapper around the hashes that you currently have, but it provides a cleaner API which also could easily documented using rdoc. This API is also easier to keep stable if the underlaying database changes for some reason and you can have deprecation warning etc.

If you like it, you could use the Null Object pattern, which would allow you to access for example the country information even if you don't have it:

ret = db.lookup('127.0.0.1')
ret.class # => MaxMindDB::Result
ret.found? # => false
ret.country.name # => nil

ret = db.lookup('74.125.225.224') # with the country DB
ret.country.name # => 'United States'
ret.city.name # => nil

Currently, if the result might be nil (or some information on it), you have to do something like this to get the English name of a city without the risk of hitting a NoMethodError on nil:

ret = db.lookup('127.0.0.1')
ret &&
  ret['city'] &&
  ret['city']['names'] &&
  ret['city']['names']['en']

I implemented it and pushed it on top of my other pull request (@14e2b95). Pick the stuff you like

The commit has been merged. Thanks for making the API easy to use.