class Shaun::Object

A SHAUN object. SHAUN objects are like Ruby hashes except they only manipulate SHAUN values.

Public Class Methods

new(hash = {}) click to toggle source

Create a SHAUN Object from a Ruby hash. Every value in the hash is casted into a SHAUN value with the to_sn method. Object values are stored as instance attributes

Example

obj = Shaun::Object.new({ greetings: 'hello' }) greetings = obj.greetings obj.greetings = 'New hello!'

# File lib/shaun.rb, line 26
def initialize(hash = {})
  hash.each_pair do |k,v|
    name = k.to_s
    metaclass.class_eval { attr_reader name.to_sym }
    create_writer name.to_sym
    instance_variable_set "@#{name}".to_sym, v.to_sn
  end
end

Public Instance Methods

method_missing(m, *params) click to toggle source

Add a new attribute to the object if the method name matches an attribute writer (i.e. whatever=) or calls the superclass' method_missing method

Calls superclass method
# File lib/shaun.rb, line 37
def method_missing(m, *params)
  res = m.match /([a-zA-Z_][a-zA-Z0-9_]*)=/
  if res and params.length == 1
    name = res[1].to_s
    metaclass.class_eval { attr_reader name.to_sym }
    create_writer name.to_sym
    instance_variable_set "@#{name}".to_sym, params[0].to_sn
  else
    super m, *params
  end
end
pretty_print(pp) click to toggle source

Pretty print the SHAUN value

# File lib/shaun.rb, line 50
def pretty_print(pp)
  pp.print_object self
end

Private Instance Methods

create_writer(sym) click to toggle source

Create an attribute writer for the given symbol that castes the value into a SHAUN value before assignment

# File lib/shaun.rb, line 62
def create_writer(sym)
  metaclass.class_eval do
    define_method(sym.to_s + "=") do |value|
      instance_variable_set "@#{sym.to_s}".to_sym, value.to_sn
    end
  end
end
metaclass() click to toggle source

Get the object's metaclass

# File lib/shaun.rb, line 56
def metaclass
  class << self ; self ; end
end