Class: Class

Inherits:
Object
  • Object
show all
Defined in:
lib/dsl_accessor.rb

Instance Method Summary collapse

Instance Method Details

#dsl_accessor(name, options = {}) ⇒ Object

Raises:

  • (TypeError)


4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/dsl_accessor.rb', line 4

def dsl_accessor(name, options = {})
  raise TypeError, "DSL Error: options should be a hash. but got `#{options.class}'" unless options.is_a?(Hash)
  writer = options[:writer] || options[:setter]
  writer =
    case writer
    when NilClass then Proc.new{|value| value}
    when Symbol   then Proc.new{|value| __send__(writer, value)}
    when Proc     then writer
    else raise TypeError, "DSL Error: writer should be a symbol or proc. but got `#{options[:writer].class}'"
    end
  write_inheritable_attribute(:"#{name}_writer", writer)

  default =
    case options[:default]
    when NilClass then nil
    when []       then Proc.new{[]}
    when {}       then Proc.new{{}}
    when Symbol   then Proc.new{__send__(options[:default])}
    when Proc     then options[:default]
    else Proc.new{options[:default]}
    end
  write_inheritable_attribute(:"#{name}_default", default)

  self.class.class_eval do
    define_method("#{name}=") do |value|
      writer = read_inheritable_attribute(:"#{name}_writer")
      value  = writer.call(value) if writer
      write_inheritable_attribute(:"#{name}", value)
    end

    define_method(name) do |*values|
      if values.empty?
        # getter method
        key = :"#{name}"
        if !inheritable_attributes.has_key?(key)
          default = read_inheritable_attribute(:"#{name}_default")
          value   = default ? default.call(self) : nil
          __send__("#{name}=", value)
        end
        read_inheritable_attribute(key)
      else
        # setter method
        __send__("#{name}=", *values)
      end
    end
  end
end