Class: KeyStruct::Base
- Inherits:
-
Object
- Object
- KeyStruct::Base
- Includes:
- Comparable
- Defined in:
- lib/key_struct/key_struct.rb
Class Attribute Summary collapse
-
.access ⇒ Object
readonly
Returns the value of attribute access.
-
.defaults ⇒ Object
readonly
Returns the value of attribute defaults.
-
.keys ⇒ Object
readonly
Returns the value of attribute keys.
Class Method Summary collapse
Instance Method Summary collapse
- #<=>(other) ⇒ Object
- #==(other) ⇒ Object
-
#initialize(args = {}) ⇒ Base
constructor
A new instance of Base.
- #inspect ⇒ Object
- #to_hash ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(args = {}) ⇒ Base
Returns a new instance of Base.
24 25 26 27 28 29 30 |
# File 'lib/key_struct/key_struct.rb', line 24 def initialize(args={}) args = self.class.defaults.merge(args) self.class.keys.each do |key| instance_variable_set("@#{key}".to_sym, args.delete(key)) end raise ArgumentError, "Invalid argument(s): #{args.keys.map(&:inspect).join(' ')} -- KeyStruct accepts #{self.class.keys.map(&:inspect).join(' ')}" if args.any? end |
Class Attribute Details
.access ⇒ Object (readonly)
Returns the value of attribute access.
21 22 23 |
# File 'lib/key_struct/key_struct.rb', line 21 def access @access end |
.defaults ⇒ Object (readonly)
Returns the value of attribute defaults.
21 22 23 |
# File 'lib/key_struct/key_struct.rb', line 21 def defaults @defaults end |
.keys ⇒ Object (readonly)
Returns the value of attribute keys.
21 22 23 |
# File 'lib/key_struct/key_struct.rb', line 21 def keys @keys end |
Class Method Details
.display_name ⇒ Object
56 57 58 |
# File 'lib/key_struct/key_struct.rb', line 56 def self.display_name self.name || "KeyStruct.#{access}" end |
Instance Method Details
#<=>(other) ⇒ Object
36 37 38 39 40 41 42 |
# File 'lib/key_struct/key_struct.rb', line 36 def <=>(other) self.class.keys.each do |key| cmp = (self.send(key) <=> other.send(key)) return cmp unless cmp == 0 end 0 end |
#==(other) ⇒ Object
32 33 34 |
# File 'lib/key_struct/key_struct.rb', line 32 def ==(other) self.class.keys.all?{|key| other.respond_to?(key) and self.send(key) == other.send(key)} end |
#inspect ⇒ Object
52 53 54 |
# File 'lib/key_struct/key_struct.rb', line 52 def inspect "<#{self.class.display_name}:0x#{self.object_id.to_s(16)} #{self.class.keys.map{|key| "#{key}:#{self.send(key).inspect}"}.join(' ')}>" end |
#to_hash ⇒ Object
44 45 46 |
# File 'lib/key_struct/key_struct.rb', line 44 def to_hash Hash[*self.class.keys.map{ |key| [key, self.send(key)]}.flatten(1)] end |
#to_s ⇒ Object
48 49 50 |
# File 'lib/key_struct/key_struct.rb', line 48 def to_s "[#{self.class.display_name} #{self.class.keys.map{|key| "#{key}:#{self.send(key)}"}.join(' ')}]" end |