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

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

Examples:

Read the value associated with a predicate.

class Person
  field :name, 'http://name'
end

person.read_attribute(:name)

Parameters:

  • name (String)

    The name of the field for which to get the value.

  • field (Field) (defaults to: nil)

    An optional Field object

Returns:

  • Native Ruby object (e.g. String, DateTime) or array of them, depending on whether the field is multivalued or not



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

Examples:

Write the value associated with a predicate.

class Person
  field :name, 'http://name'
end

person.write_attribute(:name, 'Bob')

Parameters:

  • name (String)

    The name of the field for which to set the value.

  • value (String)

    The value to set it to

  • field (Field) (defaults to: nil)

    An optional Field object

Raises:



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