Class: SRSGame::Traitable

Inherits:
Object show all
Defined in:
lib/srs_game.rb

Overview

From Dwemthy’s Array by _why the lucky stiff mislav.uniqpath.com/poignant-guide/dwemthy/

Direct Known Subclasses

Item

Class Method Summary collapse

Class Method Details

.metaclassObject

Get a metaclass for this class



139
# File 'lib/srs_game.rb', line 139

def self.metaclass; class << self; self; end; end

.traits(*arr) ⇒ Object

Advanced metaprogramming code for nice, clean traits



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/srs_game.rb', line 142

def self.traits( *arr )
  return @traits if arr.empty?

  # 1. Set up accessors for each variable
  attr_accessor *arr

  # 2. Add a new class method to for each trait.
  arr.each do |a|
    metaclass.instance_eval do
      define_method( a ) do |val|
        @traits ||= {}
        @traits[a] = val
      end # define_method
    end # instance_eval
  end # each

  # 3. For each traitable object, the `initialize' method
  #    should use the default number for each trait.
  class_eval do
    define_method( :initialize ) do
      self.class.traits.each do |k,v|
        instance_variable_set("@#{k}", v)
      end
    end
  end

end