Module: Creatable::InstanceMethods

Defined in:
lib/creatable/instance_methods.rb

Overview

Class methods that get mixed in.

Instance Method Summary collapse

Instance Method Details

#attribute(name: nil, type: 'accessor', kind_of: nil) ⇒ 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
38
39
# File 'lib/creatable/instance_methods.rb', line 18

def attribute(name: nil, type: 'accessor', kind_of: nil)
  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

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

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

#attributesArray

Returns the list of attributes attatched to this object

Returns:

  • (Array)

    the current attributes



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

def attributes
  @attributes ||= []
end

#create(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

Returns:

  • (Object)

    Newly created object



44
45
46
47
48
49
50
51
# File 'lib/creatable/instance_methods.rb', line 44

def create(args = {})
  object = new
  names = attributes.map { |e| e[:name].to_sym }
  args.each do |k, v|
    object.instance_variable_set "@#{k}".to_sym, v if names.include? k
  end
  object
end