module Toolchain::Attributes::ClassMethods
Public Instance Methods
attribute(key, type, default = nil)
click to toggle source
Defines an attribute on the Class.
@example
class Company attribute :name, String, "Unnamed" attribute :email, String end
@param key [Symbol, String] @param type [Class] @param default [Object]
# File lib/toolchain/attributes.rb, line 29 def attribute(key, type, default = nil) type = [TrueClass, FalseClass] if type == Boolean if Helpers.invalid_value?(default, type) raise Errors::TypeMismatch, "expected #{self.name}##{key} to have default value " + "of #{type} type, but received #{default.class} (#{default})." end keys.push(key.to_sym) define_method(key) do value = instance_variable_get("@#{key}") if value.nil? new_value = begin if default.kind_of?(Proc) default.call else default.dup end rescue TypeError default end send("#{key}=", new_value) else value end end define_method("#{key}=") do |value| if value.kind_of?(String) && type.respond_to?(:parse) value = type.parse(value) end if type == [TrueClass, FalseClass] && [0, "0"].include?(value) value = false end if type == [TrueClass, FalseClass] && [1, "1"].include?(value) value = true end if Helpers.invalid_value?(value, type) raise Errors::TypeMismatch, "#{self.class}##{key} expected #{type} type, " + "but received #{value.class} (#{value})." end if value.kind_of?(Hash) transformation = Configuration.hash_transformation value = Helpers.send(transformation, value) end instance_variable_set("@#{key}", value) end end
include_attributes(attributes)
click to toggle source
Takes a Proc that contains attribute definitions and applies that to this class.
@param attributes [Proc]
# File lib/toolchain/attributes.rb, line 94 def include_attributes(attributes) class_eval(&attributes) end
keys()
click to toggle source
@return [Array<Symbol>] all defined attributes.
# File lib/toolchain/attributes.rb, line 13 def keys @keys ||= [] end