Module: Creatable::ClassMethods

Defined in:
lib/creatable/class_methods.rb

Overview

Class methods that get mixed in.

Instance Method Summary collapse

Instance Method Details

#attribute(name: nil, type: 'accessor', kind_of: nil, &block) ⇒ Void

Replacement for attr_* Will build the same getter/setter methods. will also include a kind_of check.

Parameters:

  • name (String) (defaults to: nil)

    name of the attribute

  • type (String) (defaults to: 'accessor')

    accessor, reader, or writer

  • kind_of (Class) (defaults to: nil)

    class that this can be set too

Returns:

  • (Void)

Raises:

  • (ArgumentError)

    if name is not supplied

  • (ArgumentError)

    if the type is not accessor, reader, or writer



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/creatable/class_methods.rb', line 18

def attribute(name: nil, type: 'accessor', kind_of: nil, &block)
  raise ArgumentError, 'name is a required parameter' unless name
  raise ArgumentError, "type must be of type: 'accessor', 'reader', or 'writer'" unless ['accessor', 'reader', 'writer'].include? type

  generate_reader(name) if ['accessor', 'reader'].include?(type)

  if ['accessor', 'writer'].include?(type)
    if kind_of.nil?
      generate_writer(name)
    else
      kind_of = [kind_of] unless kind_of.is_a? Array
      generate_required_writer(name, kind_of)
    end
  end

  attributes.delete_if { |e| e[:name] == name } if attributes.map { |e| e[:name] }.include? name

  attributes.push(name: name, type: type, kind_of: kind_of, block: block)
  nil
end

#attributesArray

Returns the list of attributes attatched to this object

Returns:

  • (Array)

    the current attributes



6
7
8
# File 'lib/creatable/class_methods.rb', line 6

def attributes
  @attributes ||= []
end

#create(args = {}) {|object, fixed_args| ... } ⇒ Object

Create a new instance of a given object. Allows you to pass in any attribute.

Parameters:

  • args (Hash) (defaults to: {})

    key/value pairs for existing attributes

Yields:

  • (object, fixed_args)

Returns:

  • (Object)

    Newly created object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/creatable/class_methods.rb', line 42

def create(args = {})
  object = new

  fixed_args = {}
  args.each { |k, v| fixed_args.store(fix_key(k), v) }

  attributes.each do |a|
    next unless fixed_args.key? a[:name].to_sym

    value = fixed_args[a[:name].to_sym]

    if a[:block]
      a[:block].call object, value
    else
      object.instance_variable_set "@#{a[:name].to_sym}", value
    end
  end

  yield object, fixed_args if block_given?
  object
end