module ValidatedAccessors

Copyright (C) 2014 Eloy Espinaco, Gastón Ramos

Constants

VERSION

Public Instance Methods

validated_accessor(attribute, options, &block) click to toggle source
# File lib/validated_accessors.rb, line 7
def validated_accessor attribute, options, &block
  define_attribute_reader attribute
  define_attribute_writter attribute, options, &block
end

Private Instance Methods

define_attribute_reader(attribute) click to toggle source
# File lib/validated_accessors.rb, line 14
def define_attribute_reader attribute
  define_method attribute do
    instance_variable_get "@#{ attribute }"
  end
end
define_attribute_writter(attribute, options) { |value| ... } click to toggle source
# File lib/validated_accessors.rb, line 20
def define_attribute_writter attribute, options, &block
  define_method "#{ attribute }=" do |value|
    value = yield value if block_given?
    unless options[:valid].include? value
      raise ArgumentError,
        "Invalid value: #{ value } for #{ attribute }."\
        "(Valid values are: #{ options[:valid] })"
    end
    instance_variable_set "@#{ attribute }", value
  end
end