Last active
December 20, 2015 10:18
-
-
Save iHiD/6114108 to your computer and use it in GitHub Desktop.
Group Discussion Creator
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
class Creator | |
class << self | |
def create!(*args) | |
create(*args).tap do |object| | |
raise ActiveRecord::RecordInvalid.new(object) if object.new_record? | |
end | |
end | |
end | |
end |
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
class Group::DiscussionCreator < Creator | |
class EmailDecoder < ::EmailDecoder | |
def title | |
subject | |
end | |
def group | |
descriptor = email.to.first.split("@").first | |
group_url = descriptor.gsub(/^group\+/, '') | |
Group.where(url: group_url).first | |
end | |
end | |
class << self | |
def create(*args) | |
new(*args).create | |
end | |
def create_from_email(email) | |
decoder = EmailDecoder.new(email) | |
self.new(decoder.group, decoder.user, decoder.title, decoder.content).create | |
end | |
end | |
def initialize(group, user, title, content) | |
@group = group | |
@user = user | |
@title = title | |
@content = content | |
end | |
def create | |
@group.discussions.build(started_by: @user, title: @title).tap do |discussion| | |
discussion.posts.build(content: @content, user: @user) | |
discussion.save | |
after_create unless discussion.new_record? | |
end | |
end | |
def after_create | |
Group::DiscussionNotifier.delay.notify_and_email(discussion.id) | |
end | |
end |
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
class EmailDecoder | |
attr_reader :email | |
def initialize(email) | |
@email = email | |
end | |
def user | |
user_email = User::EmailAddress.where(email_address: email.from.first).first | |
user = user_email ? user_email.user : nil | |
end | |
def subject | |
email.subject | |
end | |
def content | |
body = (email.multipart?? email.text_part : email).body.decoded | |
MailExtract.new(body).body | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment