Module: Creatable::InstanceMethods
- Defined in:
- lib/creatable/instance_methods.rb
Overview
Class methods that get mixed in.
Instance Method Summary collapse
-
#attribute(name: nil, type: 'accessor', kind_of: nil) ⇒ Void
Replacement for attr_* Will build the same getter/setter methods.
-
#attributes ⇒ Array
Returns the list of attributes attatched to this object.
-
#create(args = {}) ⇒ Object
Create a new instance of a given object.
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.
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 |
#attributes ⇒ Array
Returns the list of attributes attatched to this object
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.
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 |