Module: Creatable

Defined in:
lib/creatable.rb,
lib/creatable/version.rb

Overview

include this, documentation will come.

Constant Summary collapse

VERSION =
'1.0.1'.freeze

Instance Method Summary collapse

Instance Method Details

#attribute(name: nil, type: nil, kind_of: nil) ⇒ Object

Raises:

  • (ArgumentError)


10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/creatable.rb', line 10

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

  if ['accessor', 'reader'].include?(type)
    define_method name.to_s do
      instance_variable_get "@#{name}"
    end
  end

  if ['accessor', 'writer'].include?(type)
    if kind_of.nil?
      define_method "#{name}=" do |value|
        instance_variable_set "@#{name}", value
      end
    else
      define_method "#{name}=" do |value|
        raise ArgumentError, "parameter #{name} (#{value.class}) is not a kind of (#{kind_of})" unless value.is_a?(kind_of) || value.nil?
        instance_variable_set "@#{name}", value
      end
    end
  end

  attributes.push name.to_sym
end

#attributesObject



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

def attributes
  @attributes ||= []
  @attributes
end

#create(args = {}) ⇒ Object



37
38
39
40
41
# File 'lib/creatable.rb', line 37

def create(args = {})
  object = new
  attributes.each { |l| object.send "#{l}=".to_sym, args[l] }
  object
end