summaryrefslogtreecommitdiffhomepage
path: root/lib/axlsx/util/accessors.rb
blob: f578be26564a706a8169b0b541e85da31d68501d (plain)
1
2
3
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
module Axlsx
  # This module defines some of the more common validating attribute
  # accessors that we use in Axlsx
  #
  # When this module is included in your class you can simply call
  #
  # string_attr_access :foo
  #
  # To generate a new, validating set of accessors for foo.
  module Accessors
    def self.included(base)
      base.send :extend, ClassMethods
    end

    # Defines the class level xxx_attr_accessor methods
    module ClassMethods

      # Creates one or more string validated attr_accessors
      # @param [Array] symbols An array of symbols representing the
      # names of the attributes you will add to your class.
      def string_attr_accessor(*symbols)
        validated_attr_accessor(symbols, 'validate_string')
      end

      # Creates on or more boolean validated attr_accessors
      # @param [Array] symbols An array of symbols representing the
      # names of the attributes you will add to your class.
      def boolean_attr_accessor(*symbols)
        validated_attr_accessor(symbols, 'validate_boolean')
      end

      # Template for defining validated write accessors
      SETTER = "def %s=(value) Axlsx::%s(value); @%s = value; end"

      # Creates the reader and writer access methods
      # @param [Array] symbols The names of the attributes to create
      # @param [String] validator The axlsx validation method to use when
      # validating assignation.
      # @see lib/axlsx/util/validators.rb 
      def validated_attr_accessor(symbols, validator)
        symbols.each do |symbol|
          attr_reader symbol
          module_eval(SETTER % [symbol.to_s, validator, symbol.to_s], __FILE__, __LINE__)
        end
      end
    end
  end
end