Sha256: 50adebe34f2ee3dd538554e1c8d308f2e82827b9a579c111bce7e07301d6660a

Contents?: true

Size: 1.59 KB

Versions: 1

Compression:

Stored size: 1.59 KB

Contents

module Recliner
  module Conversions
    extend self
    
    class ConversionError < TypeError
    end
    
    def clear!
      conversions.clear
    end
    
    def convert(from, to, options={})
      return nil if from.nil?
      return from if to.is_a?(Class) && from.kind_of?(to)
      
      source = options[:source] || from.class
      
      if block = conversion(source, to)
        from.instance_eval(&block) rescue nil
      else
        raise ConversionError, "No registered conversion from #{source} to #{to.inspect}"
      end
    end
    
    def convert!(from, to, options={})
      return nil if from.nil?
      return from if to.is_a?(Class) && from.kind_of?(to)
      
      source = options[:source] || from.class
      
      if block = conversion(source, to)
        begin
          from.instance_eval(&block)
        rescue => e
          raise ConversionError, "Conversion block raised exception"
        end
      else
        raise ConversionError, "No registered conversion from #{source} to #{to.inspect}"
      end
    end
    
    def register(from, to, &block)
      conversions[from][to] = block
    end
    
  private
    def conversion(from, to)
      while from
        return conversions[from][to] if conversions[from] && conversions[from][to]
        from = from.is_a?(Class) ? from.superclass : nil
      end
      nil
    end
  
    def conversions
      @conversions ||= Hash.new { |hash, key| hash[key] = {} }
    end
  end
end

Dir[File.dirname(__FILE__) + "/conversions/*.rb"].sort.each do |path|
  filename = File.basename(path)
  require "recliner/conversions/#{filename}"
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
recliner-0.0.1 lib/recliner/conversions.rb