Sha256: 143f97cc4a481971184c237f7d6300fa10be87a7651d35deb336a9c90df8db31
Contents?: true
Size: 1.96 KB
Versions: 1
Compression:
Stored size: 1.96 KB
Contents
module Creatable # Class methods that get mixed in. module ClassMethods # Returns the list of attributes attatched to this object # @return [Hash] the current attributes def attributes @attributes ||= {} @attributes end # Replacement for attr_* Will build the same getter/setter methods. # will also include a kind_of check. # @param [String] name name of the attribute # @param [String] type accessor, reader, or writer # @param [Class] kind_of class that this can be set too # @raise [ArgumentError] if name is not supplied # @raise [ArgumentError] if the type is not accessor, reader, or writer # @return [Void] def attribute(name: nil, type: 'accesor', 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 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}=") { |value| instance_variable_set "@#{name}", value } 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.merge!(name: name, type: type, kind_of: kind_of) nil end # Create a new instance of a given object. Allows you to pass in any attribute. # @param [Hash] arg key/value pairs for existing attributes # @return [Object] Newly created object def create(arg = {}) object = new key, value = arg.flatten attributes.each { |_l| object.instance_variable_set "@#{key}", value } object end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
creatable-2.0.0 | lib/creatable/class_methods.rb |