Module: Tripod::Attributes
- Extended by:
- ActiveSupport::Concern
- Included in:
- Components, EmbeddedResource
- Defined in:
- lib/tripod/attributes.rb
Overview
This module defines behaviour for attributes.
Instance Method Summary collapse
-
#read_attribute(name, field = nil) ⇒ Object
(also: #[])
Reads an attribute from this resource, based on a defined field Returns the value(s) for the named (or given) field.
-
#write_attribute(name, value, field = nil) ⇒ Object
(also: #[]=)
Writes an attribute to the resource, based on a defined field.
Instance Method Details
#read_attribute(name, field = nil) ⇒ Object Also known as: []
Reads an attribute from this resource, based on a defined field Returns the value(s) for the named (or given) field
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/tripod/attributes.rb', line 22 def read_attribute(name, field=nil) field ||= self.class.get_field(name) attr_values = read_predicate(field.predicate) if field.multivalued # If the field is multivalued, return an array of the results # just return the uri or the value of the literal. attr_values.map { |v| field.is_uri? ? v : v.object } else # If it's not multivalued, return the first (should be only) result. if field.is_uri? attr_values.first else # try to get it in english if it's there. (TODO: make it configurable what the default is) val = attr_values.select{ |v| v.language == :en }.first || attr_values.first val.object if val end end end |
#write_attribute(name, value, field = nil) ⇒ Object Also known as: []=
Writes an attribute to the resource, based on a defined field
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/tripod/attributes.rb', line 56 def write_attribute(name, value, field=nil) field ||= self.fields[name] raise Tripod::Errors::FieldNotPresent.new unless field if value.kind_of?(Array) if field.multivalued new_val = [] value.each do |v| new_val << write_value_for_field(v, field) end else new_val = write_value_for_field(value.first, field) end else new_val = write_value_for_field(value, field) end attribute_will_change!(name) write_predicate(field.predicate, new_val) end |