Module: Attributable::ClassMethods
- Defined in:
- app/models/attributable.rb
Overview
Class methods for attribute configuration
Instance Method Summary collapse
-
#association(name, instance_method, options = {}) ⇒ Object
Defines an association with the name.
-
#attribute_details_for(attribute_name) ⇒ Attributable::Attribute
Looks up the Attribute in a attribute_details Array.
-
#attribute_names ⇒ Array<String>
An array of all attribute names.
-
#custom_attribute(name, options = {}, override_previous = false) ⇒ void
Define a custom attribute with the provided name.
-
#defaults ⇒ Hash<String,Object>
Returns a hash of default attribute values.
Instance Method Details
#association(name, instance_method, options = {}) ⇒ Object
Defines an association with the name.
103 104 105 106 107 |
# File 'app/models/attributable.rb', line 103 def association(name, instance_method, = {}) association = Association.new(self, name, instance_method, ) association.configure(self) self.association_details += [association] end |
#attribute_details_for(attribute_name) ⇒ Attributable::Attribute
Looks up the Attribute in a attribute_details Array
127 128 129 130 |
# File 'app/models/attributable.rb', line 127 def attribute_details_for(attribute_name) attribute_details.detect { |d| d.name.to_sym == attribute_name.to_sym } || raise(StandardError, "Unknown attribute #{attribute_name}") end |
#attribute_names ⇒ Array<String>
Returns An array of all attribute names.
118 119 120 |
# File 'app/models/attributable.rb', line 118 def attribute_names attribute_details.map(&:name) end |
#custom_attribute(name, options = {}, override_previous = false) ⇒ void
Note:
Heavy on meta-programming here. There behaviour could also be tidied up and simplified significantly.
This method returns an undefined value.
Define a custom attribute with the provided name. Will automatically generate: - Validations - Form helpers - Accessioning tie-ins - Convert blank attributes to nil
90 91 92 93 94 95 96 97 98 99 100 |
# File 'app/models/attributable.rb', line 90 def custom_attribute(name, = {}, override_previous = false) attribute = Attribute.new(self, name, ) attribute.configure(self) if override_previous self.attribute_details = attribute_details.reject { |a| a.name == name } self.attribute_details += [attribute] elsif self.attribute_details.detect { |a| a.name == name }.nil? self.attribute_details += [attribute] end end |
#defaults ⇒ Hash<String,Object>
Returns a hash of default attribute values
112 113 114 115 |
# File 'app/models/attributable.rb', line 112 def defaults @defaults ||= attribute_details.each_with_object({}) { |attribute, hash| hash[attribute.name] = attribute.default } end |