Skip to content

Instantly share code, notes, and snippets.

@webuilder240
Created June 29, 2019 11:32
Show Gist options
  • Save webuilder240/4d8abe5f17cc95e833f433b3bb6071e8 to your computer and use it in GitHub Desktop.
Save webuilder240/4d8abe5f17cc95e833f433b3bb6071e8 to your computer and use it in GitHub Desktop.
attr_readonlyでレコード作成済みのオブジェクトへの代入でもエラーにする
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