Class: DBI::ColumnInfo

Inherits:
Hash
  • Object
show all
Defined in:
lib/dbi/columninfo.rb

Overview

This represents metadata for columns within a given table, such as the data type, whether or not the the column is a primary key, etc.

ColumnInfo is a delegate of Hash, but represents its keys indifferently, coercing all strings to symbols. It also has ostruct-like features, f.e.:

h = ColumnInfo.new({ "foo" => "bar" })
h[:foo] => "bar"
h["foo"] => "bar"
h.foo => "bar"

All of these forms have assignment forms as well.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = nil) ⇒ ColumnInfo

Create a new ColumnInfo object.

If no Hash is provided, one will be created for you. The hash will be shallow cloned for storage inside the object, and an attempt will be made to convert all string keys to symbols.

In the event that both string and symbol keys are provided in the initial hash, we cannot safely route around collisions and therefore a TypeError is raised.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/dbi/columninfo.rb', line 37

def initialize(hash=nil)
    @hash ||= Hash.new

    @hash = hash.inject({}) do |h, (key, val)|
        if String === key
            new_k = key.to_sym
            if h.has_key? new_k
                raise ::TypeError, 
                    "#{self.class.name} may construct from a hash keyed with strings or symbols, but not both"
            end
            
            h[new_k] = val
        else
            h[key] = val
        end
        
        h
    end

    super(@hash)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, value = nil) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
# File 'lib/dbi/columninfo.rb', line 71

def method_missing(sym, value=nil)
    if sym.to_s =~ /=$/
        sym = sym.to_s.sub(/=$/, '').to_sym
        @hash[sym] = value
    elsif sym.to_s =~ /\?$/
        sym = sym.to_s.sub(/\?$/, '').to_sym
        @hash[sym]
    else
        @hash[sym]
    end
end

Class Method Details

.deprecated_alias(target, source) ⇒ Object

Aliases - XXX soon to be deprecated



84
85
86
87
# File 'lib/dbi/columninfo.rb', line 84

def self.deprecated_alias(target, source) # :nodoc:
    define_method(target) { |*args| method_missing(source, *args) }
    deprecate target 
end

Instance Method Details

#[](key) ⇒ Object



59
60
61
# File 'lib/dbi/columninfo.rb', line 59

def [](key)
    @hash[key.to_sym]
end

#[]=(key, value) ⇒ Object



63
64
65
# File 'lib/dbi/columninfo.rb', line 63

def []=(key, value)
    @hash[key.to_sym] = value
end

#defaultObject

:nodoc; XXX hack to get around Hash#default



67
68
69
# File 'lib/dbi/columninfo.rb', line 67

def default() # :nodoc; XXX hack to get around Hash#default
    method_missing(:default)
end