Skip to content

Instantly share code, notes, and snippets.

@yasaichi
Last active February 24, 2020 03:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yasaichi/8444ee2e51d86f61407f3b1e1fdf8659 to your computer and use it in GitHub Desktop.
Save yasaichi/8444ee2e51d86f61407f3b1e1fdf8659 to your computer and use it in GitHub Desktop.
Strict mode of `composed_of` in Ruby on Rails
ApplicationRecord.singleton_class.prepend(Module.new do
def composed_of(part_id, options = {})
super(part_id, options.except(:strict))
return if !options[:strict] || !options[:mapping]
options[:mapping].flatten.each_slice(2) do |attr_name, _|
next if attr_name.to_sym == part_id.to_sym
define_method("#{attr_name}=") do |_val|
raise "Can't change the attributes mapped to `#{part_id}` directly."
end
end
end
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment