Class: Mumukit::Platform::Model
- Includes:
- ActiveModel::Model
- Defined in:
- lib/mumukit/platform/model.rb
Class Method Summary collapse
- .accessors ⇒ Object
-
.define_attr_readers(readers, bool_readers) ⇒ Object
Define the attribute readers for the model, given the normal accessor names and the boolean accessor names.
-
.define_attr_writers(writers, bool_writers) ⇒ Object
Define the attribute writers for the model, given the normal accessor names and the boolean accessor names.
-
.dump(obj) ⇒ Object
Serializes model.
-
.load(json) ⇒ Object
Deserializes model.
-
.model_attr_accessor(*readers) ⇒ Object
Accessors.
-
.parse(hash) ⇒ Object
Parses model from an event.
Instance Method Summary collapse
Class Method Details
.accessors ⇒ Object
39 40 41 |
# File 'lib/mumukit/platform/model.rb', line 39 def self.accessors self.readers + self.attributes.map { |it| "#{it}=".to_sym } end |
.define_attr_readers(readers, bool_readers) ⇒ Object
Define the attribute readers for the model, given the normal accessor names and the boolean accessor names
45 46 47 48 |
# File 'lib/mumukit/platform/model.rb', line 45 def self.define_attr_readers(readers, bool_readers) attr_reader(*readers) bool_readers.each { |it| define_method("#{it}?") { !!send(it) } } end |
.define_attr_writers(writers, bool_writers) ⇒ Object
Define the attribute writers for the model, given the normal accessor names and the boolean accessor names
52 53 54 55 |
# File 'lib/mumukit/platform/model.rb', line 52 def self.define_attr_writers(writers, bool_writers) attr_writer(*writers) bool_writers.each { |it| define_method("#{it}=") { |value| instance_variable_set("@#{it}", value.to_boolean) } } end |
.dump(obj) ⇒ Object
Serializes model
60 61 62 |
# File 'lib/mumukit/platform/model.rb', line 60 def self.dump(obj) obj.to_json end |
.load(json) ⇒ Object
Deserializes model
65 66 67 |
# File 'lib/mumukit/platform/model.rb', line 65 def self.load(json) json ? new(JSON.parse(json)) : new end |
.model_attr_accessor(*readers) ⇒ Object
Accessors
17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/mumukit/platform/model.rb', line 17 def self.model_attr_accessor(*readers) bools, raws = readers.partition { |it| it.to_s.end_with? '?' } raw_bools = bools.map { |it| it.to_s[0..-2].to_sym } attributes = raws + raw_bools self.readers += readers self.attributes += raws + raw_bools define_attr_readers attributes, raw_bools define_attr_writers raws, raw_bools end |
.parse(hash) ⇒ Object
Parses model from an event. Only allowed attributes are accepted
31 32 33 |
# File 'lib/mumukit/platform/model.rb', line 31 def self.parse(hash) hash ? new(hash.slice(*self.attributes)) : new end |
Instance Method Details
#as_json(options = {}) ⇒ Object
35 36 37 |
# File 'lib/mumukit/platform/model.rb', line 35 def as_json( = {}) super().slice(*self.class.attributes.map(&:to_s)) end |
#empty? ⇒ Boolean
11 12 13 |
# File 'lib/mumukit/platform/model.rb', line 11 def empty? as_json.empty? end |