Sha256: 0a71ca030458f46493022ce15798d32f65f56171f4184c961e7bd23e293fce27

Contents?: true

Size: 1.87 KB

Versions: 13

Compression:

Stored size: 1.87 KB

Contents

class Cranium::Transformation::Index

  def initialize
    @indexes = {}
  end



  def lookup(field_name, options)
    validate options

    cache = cache_for(options[:from_table], key_fields(options), field_name)

    if cache.has_key? keys(options)
      cache[keys(options)]
    elsif options.has_key? :if_not_found_then
      case options[:if_not_found_then]
        when Proc
          options[:if_not_found_then].call
        else
          options[:if_not_found_then]
      end
    elsif options.has_key? :if_not_found_then_insert
      cache[keys(options)] = Cranium::DimensionManager.for(options[:from_table], key_fields(options)).insert(field_name, default_value_record(options))
    else
      :not_found
    end
  end



  def insert(field_name, options)
    Cranium::DimensionManager.for(options[:table], [field_name]).insert(field_name, options[:record])
  end



  def validate(options)
    raise ArgumentError, "Cannot specify both :if_not_found_then and :if_not_found_then_insert options" if options.has_key? :if_not_found_then_insert and options.has_key? :if_not_found_then
  end



  private

  def default_value_record(options)
    if options.has_key? :match
      key_values = options[:match]
    else
      key_values = {options[:match_column] => options[:to_value]}
    end
    options[:if_not_found_then_insert].merge(key_values)
  end



  def cache_for(table_name, key_fields, value_field)
    @indexes[[table_name, key_fields, value_field]] ||= Cranium::DimensionManager.for(table_name, key_fields).create_cache_for_field(value_field)
  end



  def key_fields(options)
    if options.has_key? :match
      key_fields = options[:match].keys
    else
      key_fields = [options[:match_column]]
    end
    key_fields
  end



  def keys(options)
    if options.has_key? :match
      keys = options[:match].values
    else
      keys = [options[:to_value]]
    end
    keys
  end

end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
cranium-0.8.1 lib/cranium/transformation/index.rb
cranium-0.8 lib/cranium/transformation/index.rb
cranium-0.7 lib/cranium/transformation/index.rb
cranium-0.6.1 lib/cranium/transformation/index.rb
cranium-0.5 lib/cranium/transformation/index.rb
cranium-0.4.3 lib/cranium/transformation/index.rb
cranium-0.4.2 lib/cranium/transformation/index.rb
cranium-0.4.1 lib/cranium/transformation/index.rb
cranium-0.4 lib/cranium/transformation/index.rb
cranium-0.3.1 lib/cranium/transformation/index.rb
cranium-0.3.0 lib/cranium/transformation/index.rb
cranium-0.2.1 lib/cranium/transformation/index.rb
cranium-0.2.0 lib/cranium/transformation/index.rb