Skip to content

Instantly share code, notes, and snippets.

@amiel
Created April 3, 2012 01:49
Show Gist options
  • Save amiel/2288698 to your computer and use it in GitHub Desktop.
Save amiel/2288698 to your computer and use it in GitHub Desktop.
Metadata pattern
class SomeModel < ActiveRecord::Base
# These are all the things I tend to add to my activerecord model for the metadata (extension table) pattern
has_one :metadata, autosave: true, dependent: :destroy, class_name: 'SomeModelMetadata'
def metadata_with_creation
metadata_without_creation || build_metadata
end
alias_method_chain :metadata, :creation
delegate :html, :html=, :html?,
:start_at, :start_at=, :start_at?,
:finish_at, :finish_at=, :finish_at?,
to: :metadata
accepts_nested_attributes_for :metadata
# Here's one sort of generic version of inspect, but I usually end up specifying specific attributes anyway
def inspect
inspection = %w[html start_at finish_at].map do |name|
"#{ name }: #{ attribute_for_inspect(name) }"
end
super.gsub('>', inspection.join(', ') + '>')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment