Created
June 29, 2019 11:32
-
-
Save webuilder240/4d8abe5f17cc95e833f433b3bb6071e8 to your computer and use it in GitHub Desktop.
attr_readonlyでレコード作成済みのオブジェクトへの代入でもエラーにする
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ActiveRecord::ReadonlyAttributes::ClassMethods.module_eval do | |
def attr_readonly(*attributes) | |
self._attr_readonly = Set.new(attributes.map(&:to_s)) + (_attr_readonly || []) | |
attributes.each do |attr| | |
define_method attr.to_s + "=" do |text| | |
raise NoMethodError.new("NoMethodError: undefined method `#{__method__}' for #{self}", __method__, text) unless new_record? | |
super | |
end | |
end | |
end | |
end | |
class Post < ApplicationRecord | |
attr_readonly :title, :body | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment