Module: Toolchain::Attributes::ClassMethods

Defined in:
lib/toolchain/attributes.rb

Instance Method Summary collapse

Instance Method Details

#attribute(key, type, default = nil) ⇒ Object

Defines an attribute on the Class.

Examples:

class Company
  attribute :name, String, "Unnamed"
  attribute :email, String
end

Parameters:

  • key (Symbol, String)
  • type (Class)
  • default (Object) (defaults to: nil)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# 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) ⇒ Object

Takes a Proc that contains attribute definitions and applies that to this class.

Parameters:

  • attributes (Proc)


94
95
96
# File 'lib/toolchain/attributes.rb', line 94

def include_attributes(attributes)
  class_eval(&attributes)
end

#keysArray<Symbol>

Returns all defined attributes.

Returns:

  • (Array<Symbol>)

    all defined attributes.



13
14
15
# File 'lib/toolchain/attributes.rb', line 13

def keys
  @keys ||= []
end