JSON を encode, decode して"堅い"オブジェクトにするためのDSL

ここに、JSONの構造を書いた。これをRubyで表現してみるために、WebJourney::Resource モジュールを定義してみようと試みる。で、こんな感じでかければいいんじゃないか。

class WjSiteConfig
  include WebJourney::Resource
  string :title
  string :theme
  object :page_default do |m|
    m.array :meta_tags, :of => Hash
  end
  object :smtp do |m|
    m.string :host
    m.string :port
    m.string :user
    m.string :password
    m.string :auth_method
  end
  object :http do |m1|
    m1.object :timeout do |m2|
      m2.integer :open
      m2.integer :read
    end
    m1.object :proxy do |m2|
      m2.string  :host
      m2.integer :port
      m2.string  :user
      m2.string  :password
      m2.array   :except_hosts, :of => :string
    end
  end
  object :html do |m1|
    m1.object :width,  :is_a => Width
    m1.object :lwidth, :is_a => Width
    m1.object :rwidth, :is_a => Width
    m1.object :sanitized_allowed do |m2|
      m2.array :tags,       :of => :string
      m2.array :attributes, :of => :string
    end
  end
  object :account do |m|
    m.boolean :accept_email
    m.boolean :accept_open_id
  end
  class Width
    include WebJourney::Resource
    integer :value
    string  :unit
  end
end

はい、つまり、migrate で書いていたスキーマ定義が、アプリケーションのモデルに移ってきただけです。この使い方どうだろうなぁ、、、スキーマ変更時に耐えられるかどうかが不明*1

ここまできて、静的型付けの方がこのようなことは得意だなぁと思って方針を変えることに。

*1:既に投入されたデータのスキーマ整合性をアプリケーション側で担保する必要がある