Module: Tutor::Attributes::InstanceMethods

Defined in:
lib/tutor/attributes.rb

Instance Method Summary collapse

Instance Method Details

#initialize_attributes(attributes = {}) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/tutor/attributes.rb', line 35

def initialize_attributes(attributes = {})
  self.tap do |object|
    # Set any explicitly passed attribute values first
    set_attributes(attributes)
    # Then defaults last, so they can use any explicitly provided values
    default_attributes = object.class.attributes.select { |attribute| !attributes.has_key?(attribute.name) }
    default_attributes.each do |attribute|
      # Do them individually so one default can use another
      set_attribute(attribute.name, attribute.default_value_for(object))
    end
  end
end

#set_attribute(name, value) ⇒ Object

Raises:

  • (NameError)


56
57
58
59
# File 'lib/tutor/attributes.rb', line 56

def set_attribute(name, value)
  raise NameError.new("Unknown attribute!", name) unless self.class.has_attribute?(name)
  self.send("#{name.to_s}=".to_sym, value)
end

#set_attributes(attributes = {}) ⇒ Object



48
49
50
51
52
53
54
# File 'lib/tutor/attributes.rb', line 48

def set_attributes(attributes = {})
  self.tap do |object|
    attributes.each do |name, value|
      set_attribute(name, value)
    end
  end
end