Class: CTioga2::Graphics::Styles::BasicStyle

Inherits:
Object
  • Object
show all
Defined in:
lib/ctioga2/graphics/styles/base.rb

Overview

This style is the base class of a series of style objects that share one common feature: all their attributes can be set using the set_from_hash function.

todo maybe a basic MetaBuilder::Type should be associated to each attribute ???

Constant Summary collapse

OldAttrAccessor =
method(:attr_accessor)

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.attr_accessor(symbol) ⇒ Object

This redefinition of attr_accessor allows to track for the names of the attributes, while still showing them up properly documented in rdoc.



39
40
41
42
43
# File 'lib/ctioga2/graphics/styles/base.rb', line 39

def self.attr_accessor(symbol)
  @attributes ||= []
  @attributes << symbol
  OldAttrAccessor.call(symbol)
end

.attributesObject

Returns the list of attributes.



46
47
48
49
50
51
52
53
# File 'lib/ctioga2/graphics/styles/base.rb', line 46

def self.attributes
  return ( @attributes || [] ) + 
    if superclass.respond_to?(:attributes)
      superclass.attributes
    else
      []
    end
end

.from_hash(hash, name = "%s") ⇒ Object

Creates a new object from a hash specification, just as in #set_from_hash.



75
76
77
78
79
# File 'lib/ctioga2/graphics/styles/base.rb', line 75

def self.from_hash(hash, name = "%s")
  obj = self.new
  obj.set_from_hash(hash, name)
  return obj
end

Instance Method Details

#instance_variable_defined?(iv) ⇒ Boolean

Returns:

  • (Boolean)


85
86
87
88
89
90
91
92
# File 'lib/ctioga2/graphics/styles/base.rb', line 85

def instance_variable_defined?(iv)
  a = instance_variables.index(iv)
  if a && a >= 0 
    return true
  else
    return false
  end
end

#set_from_hash(hash, name = "%s") ⇒ Object

Sets the values of the attributes from the given hash. Keys are looked under the form of

name % key_name

where key_name takes all the values of the attributes.

Unspecified attributes are not removed from the object. Extra keys are silently ignored.



64
65
66
67
68
69
70
71
# File 'lib/ctioga2/graphics/styles/base.rb', line 64

def set_from_hash(hash, name = "%s")
  for key_name in self.class.attributes
    hash_key = name % key_name
    if hash.key? hash_key 
      self.send("#{key_name}=", hash[hash_key])
    end
  end
end

#to_hash(name = "%s") ⇒ Object

Converts to a hash. Does the reverse of #set_from_hash.



96
97
98
99
100
101
102
103
104
# File 'lib/ctioga2/graphics/styles/base.rb', line 96

def to_hash(name = "%s")
  retval = {}
  for attr in self.class.attributes
    if instance_variable_defined?("@#{attr}")
      retval[name % attr] = instance_variable_get("@#{attr}")
    end
  end
  return retval
end

#update_from_other(other_object) ⇒ Object

Updates information from another object.



107
108
109
# File 'lib/ctioga2/graphics/styles/base.rb', line 107

def update_from_other(other_object)
  set_from_hash(other_object.to_hash)
end