Module: ClassKit
- Defined in:
- lib/class_kit/helper.rb,
lib/class_kit/version.rb,
lib/class_kit/value_helper.rb,
lib/class_kit/class_methods.rb,
lib/class_kit/attribute_helper.rb,
lib/class_kit/exceptions/invalid_class_error.rb,
lib/class_kit/exceptions/attribute_not_found_error.rb,
lib/class_kit/exceptions/invalid_parse_value_error.rb,
lib/class_kit/exceptions/invalid_attribute_value_error.rb
Defined Under Namespace
Modules: Exceptions Classes: AttributeHelper, Helper, ValueHelper
Constant Summary collapse
- VERSION =
"0.2.1"
Instance Method Summary collapse
Instance Method Details
#attr_accessor_type(name, type: nil, collection_type: nil, allow_nil: true, default: nil, auto_init: false, meta: {}) ⇒ Object
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 50 51 52 53 54 55 56 57 |
# File 'lib/class_kit/class_methods.rb', line 2 def attr_accessor_type(name, type: nil, collection_type: nil, allow_nil: true, default: nil, auto_init: false, meta: {}) if !self.class_variable_defined?(:@@class_kit_attributes) self.class_variable_set(:@@class_kit_attributes, []) end if !self.class_variable_defined?(:@@is_class_kit_class) self.class_variable_set(:@@is_class_kit_class, true) end attributes = self.class_variable_get(:@@class_kit_attributes) attributes.push({ name: name, type: type, collection_type: collection_type, allow_nil: allow_nil, default: default, auto_init: auto_init, meta: }) self.class_variable_set(:@@class_kit_attributes, attributes) self.class_eval do define_method name do cka = self.class.class_variable_get(:@@class_kit_attributes).detect { |i| i[:name] == name } if eval("@#{name}") == nil && cka[:default] != nil eval("@#{name}=cka[:default]") end if eval("@#{name}") == nil && cka[:auto_init] == true eval("@#{name}=cka[:type].new") end return eval("@#{name}") end end self.class_eval do define_method "#{name}=" do |value| #get the attribute meta data cka = self.class.class_variable_get(:@@class_kit_attributes).detect { |i| i[:name] == name } #verify if the attribute is allowed to be set to nil if value == nil && cka[:allow_nil] == false raise ClassKit::Exceptions::InvalidAttributeValueError.new("Attribute: #{name}, must not be nil.") end #check if the value being set is not of the specified type and should attempt to parse the value if cka[:type] != nil && value != nil && (cka[:type] == :bool || !value.is_a?(cka[:type])) begin value = ClassKit::ValueHelper.instance.parse(type: cka[:type], value: value) rescue => e raise ClassKit::Exceptions::InvalidAttributeValueError.new("Attribute: #{name}, must be of type: #{cka[:type]}. Error: #{e}") end end eval("@#{name}=value") end end end |