Skip to content

Instantly share code, notes, and snippets.

@iHiD
Last active December 20, 2015 10:18
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 iHiD/6114108 to your computer and use it in GitHub Desktop.
Save iHiD/6114108 to your computer and use it in GitHub Desktop.
Group Discussion Creator
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
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
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