Class: Lac::BaseModel
- Inherits:
-
Object
- Object
- Lac::BaseModel
- Defined in:
- lib/lac/base_model.rb
Constant Summary collapse
- @@fields =
Any suggestions on how to manage these fields better are welcome!
[]
Class Method Summary collapse
Instance Method Summary collapse
- #fields ⇒ Object
- #id ⇒ Object
-
#initialize ⇒ BaseModel
constructor
A new instance of BaseModel.
- #save ⇒ Object
- #to_hash ⇒ Object
- #validates? ⇒ Boolean
Constructor Details
#initialize ⇒ BaseModel
Returns a new instance of BaseModel.
11 12 |
# File 'lib/lac/base_model.rb', line 11 def initialize end |
Class Method Details
.all ⇒ Object
44 45 46 47 48 49 50 51 52 |
# File 'lib/lac/base_model.rb', line 44 def self.all begin YAML::load_file("#{self.name}.yml") YAML::load_file("#{self.name}.yml")[:collecion] YAML::load_file("#{self.name}.yml")[:collection] rescue [] end end |
.field(symbol) ⇒ Object
19 20 21 22 23 24 |
# File 'lib/lac/base_model.rb', line 19 def self.field(symbol) @@fields.push(symbol) @@fields = @@fields.uniq attr_accessor symbol end |
.fields ⇒ Object
36 37 38 |
# File 'lib/lac/base_model.rb', line 36 def self.fields self.new.fields end |
.primary_key ⇒ Object
40 41 42 |
# File 'lib/lac/base_model.rb', line 40 def self.primary_key self.new.primary_key end |
Instance Method Details
#fields ⇒ Object
54 55 56 |
# File 'lib/lac/base_model.rb', line 54 def fields @@fields end |
#id ⇒ Object
70 71 72 73 74 |
# File 'lib/lac/base_model.rb', line 70 def id if self.validates? Digest::SHA256.hexdigest(self.method(self.primary_key).call) end end |
#save ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/lac/base_model.rb', line 58 def save filename = "#{self.class}.yml" FileUtils.touch(filename) if validates? && id collection = YAML::load_file(filename) collection = {} unless collection collection[:collection] = {} unless collection[:collection] collection[:collection][id.to_sym] = to_hash File.open(filename, 'w') {|f| f.write collection.to_yaml } end end |
#to_hash ⇒ Object
26 27 28 29 30 31 32 33 34 |
# File 'lib/lac/base_model.rb', line 26 def to_hash hash = {} @@fields.each do |field| if field hash[field] = self.method(field).call end end hash end |
#validates? ⇒ Boolean
14 15 16 17 |
# File 'lib/lac/base_model.rb', line 14 def validates? return true unless primary_key self.method(primary_key).call.present? end |