Sha256: 368d515902ce78ab0fd1d78ab65bed04ccfef843761a942bd12a37bc6ed73baf

Contents?: true

Size: 1.05 KB

Versions: 1

Compression:

Stored size: 1.05 KB

Contents

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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
bikepoa-tools-0.4.0 lib/bikepoa/helpers.rb