Module: Tripod::Attributes

Extended by:
ActiveSupport::Concern
Included in:
Components
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

Raises:



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/tripod/attributes.rb', line 22

def read_attribute(name, field=nil)
  field ||= self.fields[name]
  raise Tripod::Errors::FieldNotPresent.new unless field

  attr_values = read_predicate(field.predicate)
  attr_values.map! { |v| read_value_for_field(v, field) }

  # If the field is multivalued, return an array of the results
  # If it's not multivalued, return the first (should be only) result.

  if field.multivalued
    attr_values
  else
    attr_values.first
  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:



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/tripod/attributes.rb', line 52

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

  write_predicate(field.predicate, new_val)
end