Json and Jsonb in Hanami framework

In the past week I’ve tried Hanami, formerly Lotus. Hanami is a web framework based on Ruby, it promises fast response time, security and simplicity.

After following the getting started guide I’ve started to reproduce a simple web API written in Rails. My goal was to understand Hanami pros and cons. At some point I came across a model with a jsonb attribute. Rails supports json and jsonb out of the box if you’re using Postgres 9.2 or greater.
Hanami data mapper supports the most common Ruby data type such as String, Integer, or DateTime, but if you need to store json and jsonb types you need to customize your setup using Postgres builtin type.

Here you can find some code that exaplains how to store this type of data:

# lib/ext/pg_jsonb.rb
require 'hanami/model/coercer'
require 'sequel'
require 'sequel/extensions/pg_json'

class PGJsonb < Hanami::Model::Coercer
  def self.dump value
    ::Sequel.pg_jsonb value
  end

  def self.load value
    ::Kernel.Hash(value) unless value.nil?
  end
end
# lib/ext/pg_json.rb
require 'hanami/model/coercer'
require 'sequel'
require 'sequel/extensions/pg_json'

class PGJson < Hanami::Model::Coercer
  def self.dump value
    ::Sequel.pg_json value
  end

  def self.load value
    ::Kernel.Hash(value) unless value.nil?
  end
end
# lib/bookshelf.rb
require_relative './ext/pg_jsonb'
require_relative './ext/pg_json'
...

Hanami::Model.configure do
  # ...
  mapping do
    # ...
    collection :user do
      attribute :id,   Integer
      attribute :options_in_jsonb, PGJsonb
      attribute :options_in_json, PGJson
    end
  end
end.load!

Let’s give Hanami a chance and try to embrace Hanami’s model separation (entity / repository).

Leave a Reply

Please Login to comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.