Module: InstanceValue

Defined in:
lib/instancevalue.rb,
lib/instancevalue/version.rb,
lib/instancevalue/classmethods.rb,
lib/instancevalue/singleton_class.rb

Overview

Examples:

Overview

class Person
  include InstanceValue

  value_reader :birthday

  def initialize(birthday)
    val :birthday, birthday
  end

  def age
    (Time.now - birthday) / (60 * 60 * 24 * 365)
  end
end

person = Person.new YOUR_BIRTHDAY
person.birthday                               #=> YOUR_BIRTHDAY
person.age                                    #=> age at runtime
person.instance_eval{val :birthday, Time.now} #=> Exception

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VALUES_KEYSTORE_NAME =
:VALUES_KEYSTORE
VERSION =
'0.0.3.1'.freeze

Instance Method Summary collapse

Instance Method Details

#inspectString

Returns:

  • (String)

57
58
59
60
61
62
63
# File 'lib/instancevalue.rb', line 57

def inspect
  super.sub(/>\z/){
    _values.map{|name, value|
      " #{name}=#{value.inspect}"
    }.join + '>'
  }
end

#instance_value_defined?(name) ⇒ Boolean

Parameters:

  • name (Symbol, String)

Returns:

  • (Boolean)

Raises:

  • (TypeError)

32
33
34
35
36
# File 'lib/instancevalue.rb', line 32

def instance_value_defined?(name)
  raise TypeError unless name.instance_of?(Symbol) or name.respond_to?(:to_str)
  
  _values.has_key? name.to_sym
end

#instance_value_get(name) ⇒ Object

Parameters:

  • name (Symbol, String)

39
40
41
# File 'lib/instancevalue.rb', line 39

def instance_value_get(name)
  instance_value_defined?(name) ? _values[name.to_sym] : nil
end

#instance_value_set(name, value) ⇒ value

Parameters:

  • name (Symbol, String)

Returns:

  • (value)

45
46
47
48
49
# File 'lib/instancevalue.rb', line 45

def instance_value_set(name, value)
  raise "value(#{name}) was already bound" if instance_value_defined? name

  _values[name.to_sym] = value
end

#instance_valuesArray<Symbol>

Returns:

  • (Array<Symbol>)

52
53
54
# File 'lib/instancevalue.rb', line 52

def instance_values
  _values.keys
end