Last active

  • Download Gist
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# report.rb
# Aliased below. This will check for existing ReportDetail with matching attributes (all of them)
# And if it exists, set the ID, otherwise, set the report_period_detail object using the original method
# Not sure if there is some Railsy way of doing this...
def report_detail_with_find(attrs)
report_detail = ReportDetail.find_or_create_by_duration_and_display_duration_and_starting_month_and_period_offset(attrs[:duration],attrs[:display_duration],attrs[:starting_month],attrs[:period_offset])
# Can't use alias_method_chain as we're overwriting a setter, the = sign messes up naming conventions
# Here we're overwriting the default report_period_detail= method to first check if an exis
alias_method :report_detail_without_find, :report_detail=
alias_method :report_detail=, :report_detail_with_find
# Ensure that if our report_detail has changed, we don't update the original as others might reference this
# So instead, search for existing report_period_detail or create new
def before_update
if report_detail.changed?
# attributes method returns keys as strings, we want symbols
attrs = report_detail.attributes.symbolize_keys # convert strings to symbols
[:id, :created_at, :updated_at].each{ |attr| attrs.delete(attr) } # don't assign old, unecessary attrs to new object

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.