Module: Platanus::Enum::ClassMethods

Defined in:
lib/platanus/enum.rb

Instance Method Summary collapse

Instance Method Details

#attr_enum(_target, _module, _options = {}) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/platanus/enum.rb', line 47

def attr_enum(_target, _module, _options={})

  map = {}
  pname = _options.has_key?(:property_name) ? _options[:property_name] : (_target.to_s + '_str')

  # Extract module constants
  _module.constants.each { |cname| map[_module.const_get(cname)] = cname.to_s.downcase }

  # Add string getter
  self.send(:define_method, pname) do
    map.fetch(self.send(_target), '')
  end

  # Add string setter
  self.send(:define_method, pname + '=') do |value|
    map.each_pair do |k,v|
      if v == value
        self.send(_target.to_s + '=', k)
        return
      end
    end
    raise InvalidEnumName
  end

  # Retrieve singleton class to define new class methods
  klass = class << self; self; end

  # Add parse function
  klass.send(:define_method, 'parse_' + _target.to_s) do |value|
    value = value.to_s
    map.each_pair do |k,v|
      return k if v == value
    end
    return nil
  end

  # Add value validator (unless validation is disabled)
  self.validates _target, inclusion: { :in => map.keys } if _options.fetch(:validate, true)
end