Class: ValueClass::Attribute

Inherits:
Object
  • Object
show all
Defined in:
lib/value_class/attribute.rb

Constant Summary collapse

OPTIONS =
{
  description: "A description of the attribute.",
  default: "The default value for this parameter.",
  class_name: "The name of the value class for this attribute.  Allows for construction from a nested hash.",
  list_of_class: "Used to declare an attribute that is a list of a class.",
  required: "If true, the parameter is required",
  limit: "The set of valid values",
  insert_method: "The name of the method to create to allow inserting into a list during progressive construction"
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options) ⇒ Attribute

Returns a new instance of Attribute.



17
18
19
20
21
22
23
24
25
# File 'lib/value_class/attribute.rb', line 17

def initialize(name, options)
  if (invalid_options = options.keys - OPTIONS.keys).any?
    raise ArgumentError, "Unknown option(s): #{invalid_options.join(',')}"
  end

  @name = name.to_sym.freeze
  @options = options.freeze
  @limit = options[:limit]
end

Instance Attribute Details

#limitObject (readonly)

Returns the value of attribute limit.



5
6
7
# File 'lib/value_class/attribute.rb', line 5

def limit
  @limit
end

#nameObject (readonly)

Returns the value of attribute name.



5
6
7
# File 'lib/value_class/attribute.rb', line 5

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



5
6
7
# File 'lib/value_class/attribute.rb', line 5

def options
  @options
end

Instance Method Details

#defaultObject



65
66
67
68
69
70
71
72
# File 'lib/value_class/attribute.rb', line 65

def default
  value = options[:default]
  begin
    value.dup
  rescue TypeError
    value
  end
end

#description(prefix = "") ⇒ Object



27
28
29
30
31
32
33
# File 'lib/value_class/attribute.rb', line 27

def description(prefix = "")
  if options[:description]
    "#{prefix}#{name}: #{options[:description]}"
  else
    "#{prefix}#{name}"
  end
end

#get_value(config) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/value_class/attribute.rb', line 35

def get_value(config)
  raw_value = raw_value(config)

  cast_value = cast_value(raw_value)

  if cast_value.nil? && options[:required]
    raise ArgumentError, "must provide a value for #{name}"
  end

  if !cast_value.nil? && limit && !limit.include?(cast_value)
    raise ArgumentError, "invalid value #{cast_value.inspect} for #{name}. allowed values #{limit.inspect}"
  end

  if cast_value.nil?
    default
  else
    cast_value
  end
end

#hash_value(raw_value) ⇒ Object



55
56
57
58
59
60
61
62
63
# File 'lib/value_class/attribute.rb', line 55

def hash_value(raw_value)
  if options[:list_of_class] && raw_value.is_a?(Array)
    raw_value.map(&:to_hash)
  elsif options[:class_name] && raw_value
    raw_value.to_hash
  else
    raw_value
  end
end