Module: FedoraLens::AttributeMethods

Extended by:
ActiveSupport::Autoload, ActiveSupport::Concern
Includes:
ActiveModel::AttributeMethods
Defined in:
lib/fedora_lens/core.rb,
lib/fedora_lens/attribute_methods.rb,
lib/fedora_lens/attribute_methods/read.rb,
lib/fedora_lens/attribute_methods/write.rb,
lib/fedora_lens/attribute_methods/declarations.rb

Defined Under Namespace

Modules: ClassMethods, Declarations, Read, Write Classes: AttributeMethodCache

Constant Summary collapse

AttrNames =
Module.new {
  def self.set_name_cache(name, value)
    const_name = "ATTR_#{name}"
    unless const_defined? const_name
      const_set const_name, value.dup.freeze
    end
  end
}

Instance Method Summary collapse

Instance Method Details

#[](attr_name) ⇒ Object

Returns the value of the attribute identified by attr_name after it has been typecast (for example, “2004-12-12” in a date column is cast to a date object, like Date.new(2004, 12, 12)). It raises ActiveModel::MissingAttributeError if the identified attribute is missing.

Alias for the read_attribute method.

class Person < ActiveRecord::Base
  belongs_to :organization
end

person = Person.new(name: 'Francesco', age: '22')
person[:name] # => "Francesco"
person[:age]  # => 22

person = Person.select('id').first
person[:name]            # => ActiveModel::MissingAttributeError: missing attribute: name
person[:organization_id] # => ActiveModel::MissingAttributeError: missing attribute: organization_id


92
93
94
# File 'lib/fedora_lens/attribute_methods.rb', line 92

def [](attr_name)
  read_attribute(attr_name) { |n| missing_attribute(n, caller) }
end

#[]=(attr_name, value) ⇒ Object

Updates the attribute identified by attr_name with the specified value. (Alias for the protected write_attribute method).

class Person
  include FedoraLens
end

person = Person.new
person[:age] = '22'
person[:age] # => 22
person[:age] # => Fixnum


107
108
109
# File 'lib/fedora_lens/attribute_methods.rb', line 107

def []=(attr_name, value)
  write_attribute(attr_name, value)
end

#attribute_namesObject

Returns an array of names for the attributes available on this object.

class Person
  include FedoraLens
end

person = Person.new
person.attribute_names
# => ["id", "created_at", "updated_at", "name", "age"]


55
56
57
# File 'lib/fedora_lens/attribute_methods.rb', line 55

def attribute_names
  @attributes.keys
end

#attributesObject

Returns a hash of all the attributes with their names as keys and the values of the attributes as values.

class Person
  include FedoraLens
end

person = Person.create(name: 'Francesco', age: 22)
person.attributes
# => {"id"=>3, "created_at"=>Sun, 21 Oct 2012 04:53:04, "updated_at"=>Sun, 21 Oct 2012 04:53:04, "name"=>"Francesco", "age"=>22}


68
69
70
71
72
# File 'lib/fedora_lens/attribute_methods.rb', line 68

def attributes
  attribute_names.each_with_object({}) { |name, attrs|
    attrs[name] = read_attribute(name)
  }
end