lib/bikepoa/helpers.rb in bikepoa-tools-0.3.1 vs lib/bikepoa/helpers.rb in bikepoa-tools-0.4.0
- old
+ new
@@ -1,27 +1,37 @@
module BikePOA
module Helpers
module ForceField
- FORCED_FIELDS = {}
def self.included(base)
- base.send :extend, ClassMethods
+ 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)
- transform = FORCED_FIELDS[property.to_sym]
- value = transform.call(value) if transform
+ enforcer = enforcers[property.to_sym]
+ value = enforcer.call(value) if enforcer
super(property, value)
end
- module ClassMethods
- def force_integer(field)
- FORCED_FIELDS[field.to_sym] = lambda { |value| Integer(value) }
+ module Enforcers
+ def self.force_integer(value)
+ Integer(value)
end
- def force_utf8(field)
- FORCED_FIELDS[field.to_sym] = lambda do |value|
- new_value = value.encode('utf-8','iso-8859-1')
- (new_value.length == value.length)? new_value : value
+ 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