📎 Webclip
Reading Rails - The Adapter Pattern
Rails uses the Adapter Pattern to present a uniform interface over libraries and classes that behave differently. The article shows this with JSON parsers, database adapters, and ActiveSupport changes to DateTime and Time.
Reading notes#
- The Adapter Pattern wraps different interfaces so code can use one consistent API.
- In the example, special cases for different locator libraries quickly become hard to maintain.
- A GeoFish adapter and an ActsAsFound adapter let the rest of the code call the same method.
- MultiJSON adapts JSON libraries so ActiveSupport can switch parsers without changing every call site.
- The Oj adapter renames
:symbolize_keysto:symbol_keysbefore callingOj.load. - The Yajl adapter builds a parser with
:symbolize_keysand then parses the string. - ActiveRecord uses adapters for PostgreSQL, MySQL, and SQLite under
lib/connection_adapters. AbstractAdapterprovides shared behavior, while database-specific adapters customize it.quoted_dateinAbstractAdapterformats dates withvalue.to_s(:db).- The PostgreSQL adapter extends that result with microseconds when available.
- It also appends
BCfor negative years. - PostgreSQL and MySQL use different native SQL for
primary_keywhen creating tables. - ActiveSupport adds methods to DateTime and Time so they expose more similar APIs.
DateTime#to_iis defined through helper methods that compute seconds since the Unix epoch.- Even with these additions, DateTime and Time still differ in behavior, such as what
+ 1means. - ActiveSupport adds methods like
changeandDurationto smooth out those differences. - The article concludes that Rails uses adapters to hide many details, but developers still need to know the underlying differences.
