Class: Class

Inherits:
Object show all
Defined in:
lib/cosmos/core_ext/class.rb

Overview

COSMOS specific additions to the Ruby Class class

Instance Method Summary collapse

Instance Method Details

#instance_attr_accessor(*args) ⇒ Object

Parameters:

  • args (Array<Symbol>)

    Array of symbols which should be turned into instance variables with class method accessors (read and write)



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/cosmos/core_ext/class.rb', line 59

def instance_attr_accessor(*args)
  args.each do |arg|
    # Non-word characters (letter, number, underscore) are disallowed
    raise ArgumentError, "Non-word characters characters parsed" if arg =~ /\W/

    # Fortify: Dynamic Code Evaluation: Code Injection
    # This is true but we're whitelisting the input above
    self.class_eval("def #{arg};@#{arg};end")
    self.instance_eval("def #{arg};self.instance.#{arg};end")
    self.class_eval("def #{arg}=(arg);@#{arg} = arg;end")
    self.instance_eval("def #{arg}=(arg);self.instance.#{arg} = arg;end")
  end
end

#instance_attr_reader(*args) ⇒ Object

Creates instance variables in the class which have corresponding class method accessors. NOTE: You must define self.instance for this to work.

For example:

class MyClass
  instance_attr_reader :test
  @@instance = nil
  def self.instance
    @@instance ||= self.new
    return @@instance
  end
  def initialize
    @test = "Test"
    @@instance = self
  end

Will allow the following:

my = MyClass.new
my.test # returns "Test"
MyClass.test # returns "Test"

Parameters:

  • args (Array<Symbol>)

    Array of symbols which should be turned into instance variables with class method readers



45
46
47
48
49
50
51
52
53
54
55
# File 'lib/cosmos/core_ext/class.rb', line 45

def instance_attr_reader(*args)
  args.each do |arg|
    # Non-word characters (letter, number, underscore) are disallowed
    raise ArgumentError, "Non-word characters characters parsed" if arg =~ /\W/

    # Fortify: Dynamic Code Evaluation: Code Injection
    # This is true but we're whitelisting the input above
    self.class_eval("def #{arg};@#{arg};end")
    self.instance_eval("def #{arg};self.instance.#{arg};end")
  end
end