module Hexx module Models # @api hide # Coerces class attribute getter and setter with given type. class BaseCoercer < Struct.new(:klass, :name, :type) # Coerces class attribute's getter and setter. # # @example # BaseCoercer.new SomeModel, :name, StrippedString # BaseCoercer.coerce # # model = SomeModel.new name: "string" # model.name.class # => StrippedString def coerce coerce_setter coerce_getter end private def coerce_setter klass.class_eval( "def #{ name }; #{ type_name }.new(@#{ name }); end" ) end def coerce_getter klass.class_eval( "def #{ name }=(value); @#{ name } = #{ type_name }.new(value); end" ) end def type_name @type_name ||= type.name end end end end