Module: MetrixDB::ClassMethods

Defined in:
lib/metrix_db.rb

Instance Method Summary collapse

Instance Method Details

#[](value) ⇒ Object



72
73
74
# File 'lib/metrix_db.rb', line 72

def [](value) 
  self.on(@ref_field => value)
end

#allObject



76
77
78
79
80
81
82
# File 'lib/metrix_db.rb', line 76

def all
  result = []
  @dataset.each_with_index do |data, index| 
    result << get_from_cache(index)
  end
  result
end

#check_uniq_fields(_dataset) ⇒ Object



48
49
50
51
52
53
54
55
56
# File 'lib/metrix_db.rb', line 48

def check_uniq_fields(_dataset) 
  return unless @uniq_fields
  @uniq_fields.each_pair do |index, field_name| 
    col_data = _dataset.map {|data| data[index]}
    if col_data.uniq! 
      raise UniqueFieldError.new("Field '#{field_name}' is not unique")
    end
  end
end

#dataset(_dataset) ⇒ Object



43
44
45
46
# File 'lib/metrix_db.rb', line 43

def dataset(_dataset)
  @dataset = _dataset
  check_uniq_fields(_dataset)
end

#field(name, options = {}) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/metrix_db.rb', line 17

def field(name, options = {})
  default_options = {:uniq => true}
  options = default_options.merge(options)
  @fields ||= {}
  index = @fields.size 
  @fields[name.to_sym] = index

  @uniq_fields ||= {}
  @uniq_fields[index] = name.to_s if options[:uniq] 

  if !@ref_field
    @ref_field = name.to_sym 
  end
  if options[:ref]
    @ref_field = name.to_sym
  end

  define_method "#{name}" do  
    @data[self.class.fields[name.to_sym]]
  end
end

#fieldsObject



39
40
41
# File 'lib/metrix_db.rb', line 39

def fields
  @fields ||= {}
end

#on(conditions = {}) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/metrix_db.rb', line 58

def on(conditions={}) 
  return nil if @dataset.nil? || @fields.nil? 
  @dataset.each_with_index do |data, index|
    hash = {}
    conditions.each_pair do |k, v|
      if data[@fields[k.to_sym]] == v
        hash[k.to_sym] = v
      end
    end
    return get_from_cache(index) if hash == conditions
  end
  return nil
end