Module: Nemo::Util::Accessors

Included in:
MetaObject::Attribute, MetaObject::ValidationRule, Visitors::Visitor
Defined in:
lib/nemo/util/accessors.rb

Overview

Alternate attr_accessor methods

Instance Method Summary collapse

Instance Method Details

#bool_accessor(*symbols) ⇒ Object

Boolean syntax

class Foo
  extend Nemo::Util::Accessors
  bool_accessor :bar
end
foo = Foo.new
foo.bar = false # @bar = false (standard writer)
foo.bar         # @bar = true  (always sets to true)
foo.bar(false)  # @bar = false (call writer)
foo.bar?        # => true      (true or false)


42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/nemo/util/accessors.rb', line 42

def bool_accessor(*symbols)
  str = String.new
  class_eval { attr_accessor(*symbols) }
  symbols.each do |symbol|
    str << "
      def #{symbol}(*args)
        @#{symbol} = (args.size > 0) ? Nemo::Util.to_bool(args.first) : true
      end
      def #{symbol}?
        Nemo::Util.to_bool(@#{symbol})
      end
    "
    class_eval(str)
  end
end

#call_accessor(*symbols) ⇒ Object

Call syntax

class Foo
  extend Nemo::Util::Accessors
  call_accessor :bar
end
foo = Foo.new
foo.bar = 1   # @bar = 1 (standard writer)
foo.bar(1)    # @bar = 1 (call writer)
foo.bar       # => 1     (standard reader)


16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/nemo/util/accessors.rb', line 16

def call_accessor(*symbols)
  str = String.new
  class_eval { attr_accessor(*symbols) }
  symbols.each do |symbol|
    str << "
      def #{symbol}(*args)
        @#{symbol} = args.first if args.size > 0
        @#{symbol}
      end
    "
    class_eval(str)
  end
end

#proc_accessor(*symbols) ⇒ Object

Procedure syntax

class Foo
  extend Nemo::Util::Accessors
  proc_accessor :bar
end
foo = Foo.new
block = Proc.new { 1 }
foo.bar = block        # @bar = Proc.new { 1 } (standard writer)
foo.bar { 1 }          # @bar = Proc.new { 1 } (&block writer)
foo.bar                # @bar => <Proc:x>      (standard reader)
foo.bar.call           # => 1


71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/nemo/util/accessors.rb', line 71

def proc_accessor(*symbols)
  str = String.new
  class_eval { attr_accessor(*symbols) }
  symbols.each do |symbol|
    str << "
      def #{symbol}(&block)
        @#{symbol} = block if block_given?
        @#{symbol}
      end
    "
    class_eval(str)
  end
end