Class: JStruct::JClass
- Extended by:
- Forwardable
- Defined in:
- lib/jstruct/jclass.rb
Class Method Summary collapse
- .from(data) ⇒ Object
- .from_hash(hash) ⇒ Object
- .inherited(klass) ⇒ Object
- .set_members!(simple_members, complex_members) ⇒ Object
Instance Method Summary collapse
- #==(other) ⇒ Object
-
#initialize(attributes) ⇒ JClass
constructor
A new instance of JClass.
- #members ⇒ Object
- #to_hash ⇒ Object
- #to_s ⇒ Object (also: #inspect)
Constructor Details
#initialize(attributes) ⇒ JClass
Returns a new instance of JClass.
44 45 46 47 48 |
# File 'lib/jstruct/jclass.rb', line 44 def initialize(attributes) attributes.each do |member, value| send(:"#{member}=", value) end end |
Class Method Details
.from(data) ⇒ Object
8 9 10 11 12 13 14 15 16 |
# File 'lib/jstruct/jclass.rb', line 8 def self.from(data) case data when String then from(JSON.parse(data)) when Hash then from_hash(data) when Enumerable then data.map {|o| from(o) } when NilClass then nil else raise("Can't parse a #{data.class} into a #{self}") end end |
.from_hash(hash) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/jstruct/jclass.rb', line 18 def self.from_hash(hash) attributes = hash.inject({}) do |h, (member, value)| if complex_members.keys.include?(member.to_sym) klass = complex_members[member.to_sym] value = klass.from(value) end h.update(member.to_sym => value) end new(attributes) end |
.inherited(klass) ⇒ Object
30 31 32 33 34 35 |
# File 'lib/jstruct/jclass.rb', line 30 def self.inherited(klass) %w[ simple_members complex_members ].each do |accessor| klass.class_eval("def self.#{accessor} ; @@#{accessor} ; end", __FILE__, __LINE__ + 1) klass.class_eval("def self.#{accessor}=(val) ; @@#{accessor} = val ; end", __FILE__, __LINE__ + 1) end end |
.set_members!(simple_members, complex_members) ⇒ Object
37 38 39 40 41 42 |
# File 'lib/jstruct/jclass.rb', line 37 def self.set_members!(simple_members, complex_members) self.simple_members = simple_members self.complex_members = complex_members attr_accessor(*(simple_members + complex_members.keys)) end |
Instance Method Details
#==(other) ⇒ Object
64 65 66 |
# File 'lib/jstruct/jclass.rb', line 64 def ==(other) members.all? {|member| send(member) == other.send(member) } end |
#members ⇒ Object
50 51 52 |
# File 'lib/jstruct/jclass.rb', line 50 def members self::class.simple_members + self::class.complex_members.keys end |
#to_hash ⇒ Object
54 55 56 |
# File 'lib/jstruct/jclass.rb', line 54 def to_hash members.inject({}) {|h, k| h.update(k => send(k.to_sym)) } end |
#to_s ⇒ Object Also known as: inspect
58 59 60 |
# File 'lib/jstruct/jclass.rb', line 58 def to_s "#<jstruct #{self.class.inspect} #{to_hash.inspect} >" end |