Skip to content

Instantly share code, notes, and snippets.

@holysugar
Created December 18, 2013 06:47
Show Gist options
  • Save holysugar/8018256 to your computer and use it in GitHub Desktop.
Save holysugar/8018256 to your computer and use it in GitHub Desktop.
なんとなくプロトコル定義からデータ構造を自動生成するためのひな形
require 'hashie'
require 'pry'
class CoercionError < StandardError; end
class ValueCoercer
def initialize(name, klass)
@name = name
@klass = klass
end
def coerce(value)
case value
when @klass
value
else
raise CoercionError, "#{@name} is not #{@klass}: '#{value}'"
end
end
end
class Item < Hashie::Dash
property :name, required: true
property :price, required: true
include Hashie::Extensions::Coercion
coerce_key :name, ValueCoercer.new(:name, String)
coerce_key :price, ValueCoercer.new(:price, Integer)
end
class User < Hashie::Dash
property :id, required: true
property :name, required: true
property :item, required: true
include Hashie::Extensions::Coercion
coerce_key :id, ValueCoercer.new(:id, Integer)
coerce_key :name, ValueCoercer.new(:name, String)
coerce_key :item, Item
end
# ↑この辺まで自動生成
u1 = User.new(id: 1, name: 'hoge', item: {name: 'つえ', price: 10}) #
binding.pry
begin
u2 = User.new(id: 'illegal', name: 'hoge', item: {name: 'つえ', price: 10}) # raises CoercionError
rescue
p $!
binding.pry
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment