Class: StaticModel::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/static_model/base.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.allObject



31
32
33
# File 'lib/static_model/base.rb', line 31

def self.all
  @records ||= load_records.freeze
end

.data_pathObject



17
18
19
20
21
# File 'lib/static_model/base.rb', line 17

def self.data_path
  return if self == Base

  @data_path ||= superclass.data_path || default_data_path
end

.data_path=(data_path) ⇒ Object



23
24
25
# File 'lib/static_model/base.rb', line 23

def self.data_path=(data_path)
  @data_path = data_path
end

.default_data_pathObject



27
28
29
# File 'lib/static_model/base.rb', line 27

def self.default_data_path
  File.join(StaticModel.base_data_path, "#{name.demodulize.tableize}.yml")
end

.exists?(criteria = {}) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
58
59
60
61
# File 'lib/static_model/base.rb', line 55

def self.exists?(criteria = {})
  if criteria.is_a?(Hash)
    !!find_by(criteria)
  else
    !!find_by(primary_key => criteria)
  end
end

.find(id) ⇒ Object



43
44
45
# File 'lib/static_model/base.rb', line 43

def self.find(id)
  find_by!(primary_key => id)
end

.find_by(criteria = {}) ⇒ Object



51
52
53
# File 'lib/static_model/base.rb', line 51

def self.find_by(criteria = {})
  where(criteria).first
end

.find_by!(*args) ⇒ Object



47
48
49
# File 'lib/static_model/base.rb', line 47

def self.find_by!(*args)
  find_by(*args) || raise(NotFound)
end

.load_recordsObject



63
64
65
66
# File 'lib/static_model/base.rb', line 63

def self.load_records
  data = YAML.load_file(data_path)
  data.map { |record_attributes| new(record_attributes).freeze }
end

.primary_keyObject



9
10
11
# File 'lib/static_model/base.rb', line 9

def self.primary_key
  @primary_key ||= superclass == Base ? "id".freeze : superclass.primary_key
end

.primary_key=(primary_key) ⇒ Object



13
14
15
# File 'lib/static_model/base.rb', line 13

def self.primary_key=(primary_key)
  @primary_key = primary_key
end

.where(criteria = {}) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/static_model/base.rb', line 35

def self.where(criteria = {})
  all.select do |record|
    criteria.all? do |attribute, value|
      record.respond_to?(attribute) && record.__send__(attribute) == value
    end
  end
end

Instance Method Details

#idObject



5
6
7
# File 'lib/static_model/base.rb', line 5

def id
  defined?(super) ? super : __send__(self.class.primary_key)
end