3 ms·
Do you mean the optional type enforcement? Admittedly it's not built-in to ruby, but it's easy to replicate.. and a lot less verbose: # Implementation:
by RVuRnvbM2e 12y ago
Do you mean the optional type enforcement? Admittedly it's not built-in to ruby, but it's easy to replicate.. and a lot less verbose:
# Implementation:
module TypedAttrs
def attr_accessor_type name, type
define_method name do
instance_variable_get "@#{name}"
end
define_method "#{name}=" do |value|
raise ArgumentError unless value.is_a? type
instance_variable_set "@#{name}", value
end
end
end
# Example:
class Foo
extend TypedAttrs
attr_accessor_type :bar, Integer
end
a = Foo.new
a.bar = 5
p a.bar
a.bar = "hi" # ArgumentError
- csirac2 12y agoSure. And just for attributes, there's also delegation, read-only attributes, builders, lazy init, roles, modifiers which are enforced at construction time (if `required` is true). Moose isn't hard to implement, it's actually had quite a few alternate implementations even in Perl. Python has enthought's traits package, and I've just been pointed to https://github.com/frasertweedale/elk https://github.com/frasertweedale/elk as well. BTW it sucks to nit-pick, but the Moose version isn't any more verbose than yours: package Foo; use Moose; has 'bar' => ( isa => 'Integer' );