module BikePOA module Helpers module ForceField def self.included(base) enforcers = {} enforcer_installers = Module.new do Enforcers.methods.grep(/^force_/).each do |meth_name| define_method(meth_name) do |field| enforcers[field] = lambda { |value| Enforcers.send(meth_name, value) } end end end base.send(:extend, enforcer_installers) base.send(:define_method, :enforcers) { enforcers } end def []=(property, value) enforcer = enforcers[property.to_sym] value = enforcer.call(value) if enforcer super(property, value) end module Enforcers def self.force_integer(value) Integer(value) end def self.force_utf8(value) begin value.encode('iso-8859-1','utf-8') # a iso-8859-1 would raise here! value rescue Encoding::InvalidByteSequenceError value.encode('utf-8','iso-8859-1') end end end end end end