Skip to content

Instantly share code, notes, and snippets.

@amkisko
Created April 24, 2025 16:14
Show Gist options
  • Save amkisko/0c5e7ed2d76dd28abff933467ca40bd9 to your computer and use it in GitHub Desktop.
Save amkisko/0c5e7ed2d76dd28abff933467ca40bd9 to your computer and use it in GitHub Desktop.
Calculatable attributes concern for ActiveRecord models
module CalculatableAttributes
extend ActiveSupport::Concern
class_methods do
def calculate(attribute, &block)
attr_name = attribute.to_s.delete("?")
attr_block = block
@@calculate_methods ||= {}
@@calculate_methods[name] ||= {}
@@calculate_methods[name][attr_name] = attr_block
define_method(:"calculate_#{attr_name}") do
instance_exec(&attr_block)
end
define_method(:"calculate_#{attr_name}!") do
assign_attributes(attr_name => method(:"calculate_#{attr_name}").call)
end
define_method(attribute) do
attributes[attr_name] || method(:"calculate_#{attr_name}").call
end
unless method_defined?(:calculate_all!)
define_method(:calculate_all!) do
@@calculate_methods[name].each do |attr_name, attr_block|
method(:"calculate_#{attr_name}!").call
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment