Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Refactor model base class

  • Loading branch information...
commit 641fc48a0dc6ed5657338fdff677d961d40b99c0 1 parent 4875388
@pfleidi authored
Showing with 29 additions and 39 deletions.
  1. +25 −39 lib/mlk/model.rb
  2. +4 −0 lib/mlk/result_set.rb
View
64 lib/mlk/model.rb
@@ -8,7 +8,7 @@ class Model
include Scrivener::Validations
extend SingleForwardable
- def_delegators :all, :first, :find, :find_match
+ def_delegators :all, :[], :first, :find, :find_match
class << self
attr_accessor :storage_engine
@@ -22,19 +22,6 @@ def self.inherited(subclass)
defined_models << subclass
end
- def self.storage
- ref = Utils.pluralize(to_reference)
- Model.storage_engine.new(ref)
- end
-
- def self.default_sort_by
- :name
- end
-
- def self.[](name)
- all.first(:name => name)
- end
-
def self.all
results = storage.all.map do |path, raw_document|
document = Document.new(raw_document)
@@ -44,6 +31,12 @@ def self.all
ResultSet.new(results)
end
+ def self.add_attribute(attr)
+ @attrs ||= [ ]
+
+ @attrs << attr
+ end
+
# Manage relations between models
def self.attribute(name)
@@ -54,12 +47,6 @@ def self.attribute(name)
add_attribute(name)
end
- def self.add_attribute(attr)
- @attrs ||= [ ]
-
- @attrs << attr
- end
-
def self.attributes
if superclass.respond_to?(:attributes)
superclass.attributes + @attrs
@@ -87,39 +74,29 @@ def self.has_many(model, name, reference = to_reference)
end
end
- def self.to_reference
- self.name.downcase
- end
-
- attr_reader :document, :content, :data
+ attr_reader :document
attribute :name
def initialize(document, options = { })
@path = options[:path]
@document = document
- @content = @document.content
- @data = @document.data
end
- def attributes
- self.class.attributes
+ def content
+ document.content
end
- def validate
- assert_present(:name)
+ def data
+ document.data
end
- def template
- if @data["template"]
- @data["template"].to_sym
- else
- default_template
- end
+ def attributes
+ self.class.attributes
end
- def default_template
- self.class.name.downcase.to_sym
+ def validate
+ assert_present(:name)
end
def ==(other_model)
@@ -130,6 +107,15 @@ def save
self.class.storage.save(self.name, @document.serialize)
end
+ def self.storage
+ ref = Utils.pluralize(to_reference)
+ Model.storage_engine.new(ref)
+ end
+
+ def self.to_reference
+ self.name.downcase
+ end
+
end
end
View
4 lib/mlk/result_set.rb
@@ -40,6 +40,10 @@ def size
alias_method :length, :size
+ def [](name)
+ first(:name => name)
+ end
+
def first(filters = {})
find(filters).results.first
end
Please sign in to comment.
Something went wrong with that request. Please try again.