Module: Frenchy::Model
- Defined in:
- lib/frenchy/model.rb
Defined Under Namespace
Modules: ClassMethods
Class Method Summary collapse
Instance Method Summary collapse
-
#attributes ⇒ Object
Return a hash of field name as string and value pairs.
-
#decorate ⇒ Object
Decorate the model using a decorator inferred by the class.
-
#initialize(attrs = {}) ⇒ Object
Create a new instance of this model with the given attributes.
-
#inspect ⇒ Object
Return a string representing the value of the model instance.
Class Method Details
.included(base) ⇒ Object
3 4 5 6 7 8 9 10 11 12 |
# File 'lib/frenchy/model.rb', line 3 def self.included(base) base.class_eval do cattr_accessor :fields, :defaults self.fields = {} self.defaults = {} end base.extend(ClassMethods) end |
Instance Method Details
#attributes ⇒ Object
Return a hash of field name as string and value pairs
24 25 26 |
# File 'lib/frenchy/model.rb', line 24 def attributes Hash[self.class.fields.map {|k,_| [k.to_s, send(k)]}] end |
#decorate ⇒ Object
Decorate the model using a decorator inferred by the class
34 35 36 37 |
# File 'lib/frenchy/model.rb', line 34 def decorate decorator_class = "#{self.class.name}Decorator".constantize decorator_class.decorate(self) end |
#initialize(attrs = {}) ⇒ Object
Create a new instance of this model with the given attributes
15 16 17 18 19 20 21 |
# File 'lib/frenchy/model.rb', line 15 def initialize(attrs={}) self.class.defaults.merge((attrs || {}).reject {|k,v| v.nil? }).each do |k,v| if self.class.fields[k.to_sym] send("#{k}=", v) end end end |
#inspect ⇒ Object
Return a string representing the value of the model instance
29 30 31 |
# File 'lib/frenchy/model.rb', line 29 def inspect "<#{self.class.name} #{attributes.map {|k,v| "#{k}: #{v.inspect}"}.join(", ")}>" end |