Module: Typingpool::Utility::Castable

Included in:
Filer, Filer::Files
Defined in:
lib/typingpool/utility/castable.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(receiver) ⇒ Object



37
38
39
# File 'lib/typingpool/utility/castable.rb', line 37

def self.included(receiver)
  receiver.extend(ClassMethods)
end

Instance Method Details

#as(sym, *args) ⇒ Object

Cast this object instance to a relative class. Call this from super in your own class if you want to pass args to the relative class constructor. All args after the first will be passed to new.

A relative class can be a subclass and in some cases a sibling class, parent class, parent sibling class, grandparent class, grandparent sibling class, and so on. A relative class will never be higher up the inheritance tree than the subclasses of the class where Castable was included.

Params

sym

Symbol corresponding to relative class to cast into. For

example, Class#as(:audio) will cast into a Class::Audio
and Class#as(:csv) will cast into Class::CSV. Casting
is class insensitive, which means you can't have class
CSV and class Csv. To cast into a related class whose
name is not not directly under that of its parent, you
must either specify the full name,
e.g. Class#as(:foo_bar_baz) to cast to Foo::Bar::Baz,
or a name relative to the parent,
e.g. Class#as(:remote_html), where Class::Remote does
not inherit from Class but Class::Remote::HTML does.

Returns

New instance of subclass



29
30
31
32
33
34
35
# File 'lib/typingpool/utility/castable.rb', line 29

def as(sym, *args)
  if klass = self.class.relative_klass(sym.to_s.downcase)
    klass.new(*args)
  else
    raise Error, "Can't find class '#{sym.to_s}' to cast to"
  end #if subklass =...
end