Skip to content

Instantly share code, notes, and snippets.

@carlosramireziii
Last active September 30, 2017 14:49
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 carlosramireziii/3bf612314b61df56a9bf444fbe458544 to your computer and use it in GitHub Desktop.
Save carlosramireziii/3bf612314b61df56a9bf444fbe458544 to your computer and use it in GitHub Desktop.
Maintaining different formats of an attribute for an ActiveRecord model
# db/schema
create_table "product_versions", force: true do |t|
t.string "string"
t.text "changelog_as_markdown"
t.text "changelog_as_html" # OPTIONAL - used for caching in Options 2 & 3 below
end
# Option 1: calculate HTML version of the changelog on-the-fly
class ProductVersion < ActiveRecord::Base
def changelog_as_html
if changelog_as_markdown.present?
markdown.parse(changelog_as_markdown)
end
end
end
# Option 2: override Markdown setter to also set HTML
class ProductVersion < ActiveRecord::Base
def changelog_as_markdown=(value)
super
if changelog_as_markdown.present?
self.changelog_as_html = markdown.parse(changelog_as_markdown)
end
end
end
# Option 3: persist HTML changelog to the database using callbacks
class ProductVersion < ActiveRecord::Base
before_save :set_changelog_as_html
private
def set_changelog_as_html
if changelog_as_markdown.present?
self.changelog_as_html = markdown.parse(changelog_as_markdown)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment