Class: Model
- Inherits:
-
Object
- Object
- Model
- Defined in:
- lib/model.rb,
lib/model/version.rb
Constant Summary collapse
- VERSION =
"0.1.1"
Class Attribute Summary collapse
Class Method Summary collapse
- .inherited(subclass) ⇒ Object
-
.key(symbol, &block) ⇒ Object
define a key and an optional block that provides a default value for the key.
Instance Method Summary collapse
- #[](key) ⇒ Object
-
#initialize(hash = {}) ⇒ Model
constructor
A new instance of Model.
- #keys ⇒ Object
Constructor Details
#initialize(hash = {}) ⇒ Model
Returns a new instance of Model.
30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/model.rb', line 30 def initialize(hash={}) unknown = hash.keys - keys if unknown.count > 0 raise ArgumentError, "unknown keyword#{'s' if unknown.count > 1}: #{unknown.join', '}" end hash.each_pair {|key, v| instance_variable_set "@#{key}", v} (self.class.defaults.keys - hash.keys).each do |key| block = self.class.defaults[key] instance_variable_set("@#{key}", instance_exec(&block)) end end |
Class Attribute Details
.defaults ⇒ Object
13 14 15 |
# File 'lib/model.rb', line 13 def defaults @defaults ||= {} end |
.keys ⇒ Object
9 10 11 |
# File 'lib/model.rb', line 9 def keys @keys ||= [] end |
Class Method Details
.inherited(subclass) ⇒ Object
17 18 19 20 |
# File 'lib/model.rb', line 17 def inherited(subclass) subclass.keys = keys.dup subclass.defaults = defaults.dup end |
.key(symbol, &block) ⇒ Object
define a key and an optional block that provides a default value for the key
23 24 25 26 27 |
# File 'lib/model.rb', line 23 def key(symbol, &block) keys << symbol unless @keys.include? symbol attr_accessor symbol defaults[symbol] = block if block end |
Instance Method Details
#[](key) ⇒ Object
46 47 48 |
# File 'lib/model.rb', line 46 def [] key send key end |
#keys ⇒ Object
42 43 44 |
# File 'lib/model.rb', line 42 def keys self.class.keys end |