lib/moosex.rb in moosex-0.0.1 vs lib/moosex.rb in moosex-0.0.2

- old
+ new

@@ -9,15 +9,19 @@ def self.included(o) o.extend(MooseX::Core) - o.class_exec { - @@meta = MooseX::Meta.new() - } - o.define_singleton_method :__meta do - class_variable_get "@@meta".to_sym + o.class_exec do + meta = MooseX::Meta.new() + + #class_variable_set "@@meta".to_sym, meta + + define_singleton_method :__meta do + meta + # class_variable_get "@@meta".to_sym + end end def initialize(args={}) self.class.__meta().init(self, args) @@ -28,18 +32,29 @@ module Core def has(attr_name, attr_options) attr = MooseX::Attribute.new(attr_name, attr_options) + g = attr.generate_getter - define_method attr_name, &g + define_method attr_name, &g - s = attr.generate_setter - - define_method "#{attr_name}=", &s + s = attr.generate_setter + + if attr_options[:is].eql? :rw + define_method "#{attr_name}=", &s + + elsif attr_options[:is].eql? :rwp + + define_method "#{attr_name}=", &s + + private "#{attr_name}=" + + end + __meta.add(attr) end end @@ -55,16 +70,29 @@ value = nil if args.has_key? @attr_symbol value = args[ @attr_symbol ] elsif @options[:required] - raise "ops, attr #{@attr_symbol} is required" + raise "attr \"#{@attr_symbol}\" is required" else value = (@options[:default].is_a? Proc) ? @options[:default].call : @options[:default] end - object.send( setter, value ) + if @options[:is].eql? :ro + + # TODO: remove redundancy + + inst_variable_name = "@#{@attr_symbol}".to_sym + type_check = generate_type_check + type_check.call(value) + object.instance_variable_set inst_variable_name, value + + else + + object.send( setter, value ) + + end end def generate_getter inst_variable_name = "@#{@attr_symbol}".to_sym Proc.new { instance_variable_get inst_variable_name } @@ -79,12 +107,15 @@ end end def generate_type_check if @options.has_key? :isa - klass = @options[:isa] + isa = @options[:isa] + + return isa if isa.is_a? Proc + return lambda do |new_value| - raise "isa check for \"#{@attr_symbol}\" failed: lol is not #{klass}!" unless new_value.is_a? klass + raise "isa check for \"#{@attr_symbol}\" failed: lol is not #{isa}!" unless new_value.is_a? isa end end lambda { |new_value| } end \ No newline at end of file