ruby 装饰器与表单对象与服务对象?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 装饰器与表单对象与服务对象?相关的知识,希望对你有一定的参考价值。

class FacebookCommentNotifer
  def initialize(comment)
    @comment = comment
  end

  def save
    @comment.save && post_to_wall
  end

  private

  def post_to_wall
    Facebook.post(title: @comment.title, user: @comment.author)
  end
end

class CommentsController < ApplicatinController
  def create
    @comment = Comment.new(params[:comment])
    if FacebookCommentNotifer.new(@comment).save
      redirect_to blog_path, notice: "Your comment was posted."
    else
      render "new"
    end
  end
end
class CommentForm
  include ActiveModel::Model

  attr_accessor :title, :author

  # validations

  def submit(params)
    return false unless valid?

    comment = create_comment(params)
    post_to_wall(comment)
    true
  end

  private

  def create_comment(params)
    Comment.create(params)
  end

  def post_to_wall(comment)
    Facebook.post(title: comment.title, user: comment.author)
  end
end

class CommentsController < ApplicatinController
  def create
    @comment_form = CommentForm.new
    if @comment_form.submit(params[:comment])
      redirect_to blog_path, notice: "Your comment was posted."
    else
      render "new"
    end
  end
end
class CommentNotifier
  def self.create(params)
    comment = Comment.new(params)
    if comment.save
      Facebook.post(title: comment.title, user: comment.author)
    end

    comment
  end
end

class CommentsController < ApplicatinController
  def create
    @comment = CommentNotifier.create(params[:comment])
    if @comment.persisted?
      redirect_to blog_path, notice: "Your comment was posted."
    else
      render "new"
    end
  end
end

以上是关于ruby 装饰器与表单对象与服务对象?的主要内容,如果未能解决你的问题,请参考以下文章

Ruby on Rails 模式 - 装饰器与演示器

迭代器与装饰器

如何在 QML 中将 @pyqtSlot 装饰器与其他装饰器一起使用?

Python装饰器与面向切面编程

装饰器,迭代器与生成器

Python 迭代器与生成器及装饰器