Last active
August 29, 2015 14:02
-
-
Save firedev/644b41967cf6c1c9d035 to your computer and use it in GitHub Desktop.
Creates :meta from given :body when saving models
This file contains 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
# app/models/concerns/metable_model.rb | |
# | |
# https://gist.github.com/firedev/644b41967cf6c1c9d035 | |
# | |
# Usage: | |
# | |
# rails g migration addMetaToModel meta:string | |
# | |
# include MetableModel | |
# metable [:meta] [, :body] [, &block] | |
# | |
# Creates :meta from given :body when saving models if no :meta given | |
# Truncates first line up to the 160 chars/first full stop whichever comes first | |
# or runs :body through a &block: | |
# | |
# include MetableModel | |
# metable | |
# | |
# or you can pass a block with your own handler: | |
# metable(:meta) { |body| body.truncate(100) } | |
# | |
module MetableModel | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def metable(meta_attr = :meta, body_attr = :body, &block) | |
before_validation { create_meta(body_attr, meta_attr, &block) } | |
# validates meta_attr, presence: true | |
end | |
end | |
def create_meta(body_attr, meta_attr, &block) | |
return if send(body_attr).blank? || send(meta_attr).present? | |
send "#{meta_attr}=", create_meta_from(body_attr, &block) | |
end | |
def create_meta_from(body_attr, &_block) | |
if block_given? | |
yield send(body_attr).to_s | |
else | |
send(body_attr).to_s | |
.split("\n")[0] | |
.to_s.split('.')[0] | |
.to_s | |
.truncate(160, separator: '.') | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment