public
Description: Rails Plugin - specify attributes within a model that can be set but not modified
Homepage: http://6brand.com
Clone URL: git://github.com/JackDanger/immutable_attributes.git
Search Repo:
immutable_attributes / lib / immutable_attributes.rb
100644 22 lines (19 sloc) 0.553 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
module ImmutableErrors
  class ImmutableAttributeError < ActiveRecord::ActiveRecordError
  end
end
 
ActiveRecord.send :include, ImmutableErrors
 
module ImmutableAttributes
  def attr_immutable(*args)
    args.each do |meth|
      class_eval do
        define_method("#{meth}=") do |value|
          new_record? || read_attribute(meth).nil? ?
            write_attribute(meth, value) :
            raise(ActiveRecord::ImmutableAttributeError, "#{meth} is immutable!")
        end
      end
    end
  end
end
 
ActiveRecord::Base.extend ImmutableAttributes