Sha256: 79289416ed1db53a7b86a901348c1c0e09aa250db25a828481ad67678e9c4081

Contents?: true

Size: 720 Bytes

Versions: 9

Compression:

Stored size: 720 Bytes

Contents

class Module

  # Like attr_writer, but the writer method validates the
  # setting against the given block.
  #
  # CREDIT: ?

  def attr_validator(*symbols, &validator)
    made = []
    symbols.each do |symbol|
      define_method "#{symbol}=" do |val|
        unless validator.call(val)
          raise ArgumentError, "Invalid value provided for #{symbol}"
        end
        instance_variable_set("@#{symbol}", val)
      end
      made << "#{symbol}=".to_sym
    end
    made
  end

  # Create aliases for validators.

  def alias_validator(*args)
    orig = args.last
    args = args - [orig]
    args.each do |name|
      #alias_method(name, orig)
      alias_method("#{name}=", "#{orig}=")
    end
  end

end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
facets-2.9.0 lib/tour/facets/module/attr_validator.rb
facets-2.9.0.pre.2 lib/tour/facets/module/attr_validator.rb
facets-2.9.0.pre.1 lib/tour/facets/module/attr_validator.rb
facets-2.8.4 lib/more/facets/module/attr_validator.rb
facets-2.8.3 lib/more/facets/module/attr_validator.rb
facets-2.8.2 lib/more/facets/module/attr_validator.rb
facets-2.8.1 lib/more/facets/module/attr_validator.rb
facets-2.8.0 lib/more/facets/module/attr_validator.rb
facets-2.7.0 lib/more/facets/module/attr_validator.rb