Module: WriteOnce::ClassMethods

Defined in:
lib/write_once.rb

Instance Method Summary collapse

Instance Method Details

#attr_write_once(*attributes) ⇒ Object

Attributes listed as write_once will be used to create a new record. Assigning a new value to a write_once attribute that is NOT currently nil and is attempting to be changed on a persisted record raises an error.

Examples

class Post < ActiveRecord::Base
  attr_write_once :title
end

post = Post.create!(title: "Introducing Ruby on Rails!")
post.title = "a different title" # raises write_onceAttributeError
post.update(title: "a different title") # raises write_onceAttributeError

post_with_nil = Post.create!(title: nil)
post_with_nil.title = "a different title" # works fine

post_with_nil2 = Post.create!(title: nil)
post_with_nil2.update(title: "a different title") # works fine


46
47
48
49
50
# File 'lib/write_once.rb', line 46

def attr_write_once(*attributes)
  self._attr_write_once |= attributes.map(&:to_s)

  include(HasWriteOnceAttributes)
end

#write_once_attribute?(name) ⇒ Boolean

:nodoc:

Returns:

  • (Boolean)


57
58
59
# File 'lib/write_once.rb', line 57

def write_once_attribute?(name) # :nodoc:
  _attr_write_once.include?(name)
end

#write_once_attributesObject

Returns an array of all the attributes that have been specified as write_once.



53
54
55
# File 'lib/write_once.rb', line 53

def write_once_attributes
  _attr_write_once
end