Skip to content
bakkdoor edited this page Nov 2, 2011 · 17 revisions

Class Definitions

Defining classes works similar to how its done in Ruby. A class definition itself is a valid expression, returning the class object you just defined. In Fancy, everything is an expression that yields a value (possibly nil).

Example:

class Person {
  # This is similar to Ruby's attr_accessor()
  # In this case *Person* could be exchanged for *self* since *self* refers to the
  # class itself within a class definition. The same is the case for class method definitions (see below). 
  read_write_slots: ('name, 'age, 'city)

  # using an instance variable as the parameter auto-assign's 
  # the instance variable with the value of the parameter.
  # { and } are optional if the method's body is empty
  def initialize: @name age: @age city: @city 

  def to_s {
    # Documentation string for this class method
    # If the first expression in a method or class definition is a string literal, it's taken as the docstring
    """
    Returns a @String@ represensation of @self.
    """
    
    "Person: #{@name} with age: #{@age} living in: #{@city}"
  }
}

# Usage:

# initialize new Person
p = Person new: "John Foo" age: 42 city: "New York"
p to_s # => "Person: John Foo with age: 42 living in: New York"

Nested Classes

Fancy also allows classes to be nested, which can be used for namespace/module like behaviour known from other languages:

class Outer {
  class Inner {
    class InnerMost {
      def foobar {
        "foobar!"
      }
    }
  }
}
instance = Outer Inner InnerMost new
instance foobar println # prints: "foobar!" 

You can open the InnerMost class like this:

class Outer Inner InnerMost {
  # To define a singleton method:
  def self barbaz {
    "barbaz!" println
  }
}

Outer Inner InnerMost barbaz # prints "barbaz!"

Or define a singleton method on InnerMost class directly:

def Outer Inner InnerMost qux {
  "Qux!" println
}

Outer Inner InnerMost qux # prints "Qux!"

Class hierarchy

As in Ruby & Smalltalk, every value within Fancy is an object, an instance of a class. Fancy’s class hierarchy has the Object class at the root. Classes themself are instances of the Class class, which in turn inherits from the Object class.
Thus classes are objects and can be created at runtime. In fact, a class definition (as seen above) does nothing more than creating a new Class object and evaluate the code in its context (self referring to the class).