Last active
September 30, 2017 14:49
-
-
Save carlosramireziii/3bf612314b61df56a9bf444fbe458544 to your computer and use it in GitHub Desktop.
Maintaining different formats of an attribute for an ActiveRecord model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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