Module: SimpleObjects::Base
- Included in:
- SimpleObjects
- Defined in:
- lib/simple_objects/base.rb
Defined Under Namespace
Modules: ClassMethods
Class Method Summary collapse
Instance Method Summary collapse
- #as_json(opts = {}) ⇒ Object
- #cache_key ⇒ Object
- #initialize(attributes = {}) ⇒ Object
- #to_h ⇒ Object
Class Method Details
.included(base) ⇒ Object
6 7 8 |
# File 'lib/simple_objects/base.rb', line 6 def self.included(base) base.extend(ClassMethods) end |
Instance Method Details
#as_json(opts = {}) ⇒ Object
44 45 46 |
# File 'lib/simple_objects/base.rb', line 44 def as_json(opts = {}) to_h.as_json(opts) end |
#cache_key ⇒ Object
48 49 50 51 |
# File 'lib/simple_objects/base.rb', line 48 def cache_key individual_key = [@id || 'new', @updated_at].reject(&:nil?).join('-') "#{self.class.to_s.underscore}/#{individual_key}" end |
#initialize(attributes = {}) ⇒ Object
22 23 24 25 26 27 28 |
# File 'lib/simple_objects/base.rb', line 22 def initialize(attributes = {}) values = defaults.merge(attributes) values.each do |attr, value| mthd = "#{attr}=" send(mthd, value) if self.respond_to?(mthd) end end |
#to_h ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/simple_objects/base.rb', line 30 def to_h attributes.each_with_object({}) do |k, hsh| val = send(k) if val.nil? val = nil elsif val.respond_to?(:to_h) val = val.to_h elsif val.respond_to?(:map) val = val.map { |v| v.respond_to?(:to_h) ? v.to_h : v } end hsh[k] = val end end |