Created
August 18, 2015 19:22
-
-
Save ttilberg/f49b6341ca019cb2f973 to your computer and use it in GitHub Desktop.
Test if @properties are set and not empty
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'pry' | |
class Thing | |
REQUIRED = [:a,:b,:c] | |
attr_accessor :a, :b, :c, :d | |
def initialize( a: '', b: '', c: '', d: '') | |
@a = a.to_s | |
@b = b.to_s | |
@c = c.to_s | |
@d = d.to_s | |
end | |
def valid? | |
puts "Testing validity: #{self}.valid?" | |
has_required_properties_shortform? | |
end | |
def has_required_properties_longform? | |
puts "Testing Required Properties: #{self}.has_required_properties?" | |
valid = true | |
REQUIRED.each do |prop| | |
print "Testing #{prop}" | |
if instance_variable_get("@#{prop}").to_s.empty? | |
print " - #{prop} was empty." | |
valid = false | |
end | |
puts | |
end | |
valid | |
end | |
def has_required_properties_shortform? | |
# Enumerable#none? iterates a code block through the collection, | |
# and returns false if any iteration returns false, otherwise true. | |
REQUIRED.none? { |prop| instance_variable_get("@#{prop}").to_s.empty? } | |
end | |
def other_test | |
true | |
end | |
end | |
a = Thing.new() | |
b = Thing.new(a: "1234") | |
c = Thing.new(a: "1234", b: 13, c:"135135") | |
d = Thing.new(a: "1234", b: "13", c:"135135", d:"1555") | |
puts a.valid? # false | |
puts b.valid? # false | |
puts c.valid? # true | |
puts d.valid? # true | |
a.a= 'hotdog' | |
a.b= 'pizza' | |
a.c= 'wowow' | |
a.d= 'yeeaahahh' | |
puts a.valid? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment