Class: KeyStruct::Base

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/key_struct/key_struct.rb

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ Base

Returns a new instance of Base.

Raises:

  • (ArgumentError)


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

.accessObject (readonly)

Returns the value of attribute access.



21
22
23
# File 'lib/key_struct/key_struct.rb', line 21

def access
  @access
end

.defaultsObject (readonly)

Returns the value of attribute defaults.



21
22
23
# File 'lib/key_struct/key_struct.rb', line 21

def defaults
  @defaults
end

.keysObject (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_nameObject



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

#inspectObject



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_hashObject



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_sObject



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