Skip to content

Instantly share code, notes, and snippets.

@chriswright47
Created August 14, 2015 18:42
Show Gist options
  • Save chriswright47/f00a8af5b1f9df249618 to your computer and use it in GitHub Desktop.
Save chriswright47/f00a8af5b1f9df249618 to your computer and use it in GitHub Desktop.

Revisions

  1. chriswright47 created this gist Aug 14, 2015.
    43 changes: 43 additions & 0 deletions checked_attr_challenge.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    # CheckedAttributes Challenge
    module CheckedAttributes
    class ValidationError < StandardError; end

    def self.included(base)
    base.extend(self)
    end

    def attr_checked attribute, &block
    attr_reader attribute

    define_method "#{attribute}=" do |value|
    raise ValidationError unless block.call(value)

    instance_variable_set("@#{attribute}", value)
    end
    end
    end

    class Person
    include CheckedAttributes

    attr_checked :age do |v|
    v >= 18
    end
    end

    require "minitest/autorun"

    describe "CheckedAttributes" do
    before do
    @subject = Person.new
    end

    it "raises an error if the validation fails" do
    @subject .age = 18
    assert_equal @subject .age, 18
    end

    it "raises an error if the validation fails" do
    assert_raises(CheckedAttributes::ValidationError) { @subject.age = 12 }
    end
    end