Class: CleanModel::Attribute
- Inherits:
-
Object
- Object
- CleanModel::Attribute
- Defined in:
- lib/clean_model/attribute.rb
Instance Attribute Summary collapse
-
#name ⇒ Object
readonly
Returns the value of attribute name.
-
#options ⇒ Object
readonly
Returns the value of attribute options.
Instance Method Summary collapse
- #assign_default(model) ⇒ Object
-
#initialize(name, options = {}) ⇒ Attribute
constructor
A new instance of Attribute.
- #transform(value) ⇒ Object
- #validate!(value) ⇒ Object
Constructor Details
#initialize(name, options = {}) ⇒ Attribute
5 6 7 8 |
# File 'lib/clean_model/attribute.rb', line 5 def initialize(name, ={}) @name = symbolize(name) @options = end |
Instance Attribute Details
#name ⇒ Object (readonly)
Returns the value of attribute name.
3 4 5 |
# File 'lib/clean_model/attribute.rb', line 3 def name @name end |
#options ⇒ Object (readonly)
Returns the value of attribute options.
3 4 5 |
# File 'lib/clean_model/attribute.rb', line 3 def @options end |
Instance Method Details
#assign_default(model) ⇒ Object
36 37 38 39 |
# File 'lib/clean_model/attribute.rb', line 36 def assign_default(model) default_value = @options[:default].is_a?(Proc) ? @options[:default].call : @options[:default] model.send("#{@name}=", default_value) if !default_value.nil? && model.respond_to?("#{@name}=") end |
#transform(value) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/clean_model/attribute.rb', line 14 def transform(value) if @options[:transformation] @options[:transformation].call(value) elsif value.is_a?(Hash) && klass.new.respond_to?(:assign_attributes) obj = klass.new obj.assign_attributes value obj elsif value.is_a?(Array) && collection_class.instance_methods.include?(:assign_attributes) value.map do |v| if v.is_a? collection_class v else obj = collection_class.new obj.assign_attributes v obj end end else value end end |
#validate!(value) ⇒ Object
10 11 12 |
# File 'lib/clean_model/attribute.rb', line 10 def validate!(value) raise InvalidTypeAssignment.new(name, value) unless value.is_a? klass end |