Skip to content

Instantly share code, notes, and snippets.

@mayra-cabrera
Last active February 23, 2016 15:58
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 mayra-cabrera/10d84c392f75d55c618e to your computer and use it in GitHub Desktop.
Save mayra-cabrera/10d84c392f75d55c618e to your computer and use it in GitHub Desktop.
Ruby patterns example

Null Object Pattern

Definir una clase que se comporte de las diferentes formas que esperas

class GeneralComment
  def self.find comment_id
    @comment = Comment.find(comment_id) || MissingComment.new
  end
end

class MissingComment
  def user_name
    "[deleted]"
  end
end

class Comment
  def user_name
    user.name
  end
end

Usar esa clase en el controlador

class CommentsController
  def show
    @comment = GeneralComment.find(params[:id])
  end
end

Y en la vista (ya sin un cochino if :D)

@comment.user_name

### Decorator Pattern

Para no ensuciar al modelo con métodos que solo son ocupados en la vista, podemos crear un decorator

class CommentDecorator 
  def initialize comment
    @comment = comment
  end
  
  def user_name
    @comment.user.name ? @comment.user.name : "deleted"
  end
end

En el controlador

class CommentsController
  def show
    comment = Comment.find(params[:id])
    @comment = CommentDecorator.new comment 
  end
end

Y en la vista

@comment.user_name

En este caso necesitas hacer override de method_missing y respond_to_missing, porque la clase CommentDecorator no tiene acceso al resto de los métodos de Comment. O también hay una gema drapper q te hace todo eso


También podrías usar un helper. Este enfoque es más simple, pero no es totalmente orientado a objetos :P

def user_name comment
  comment.user ? comment.user.name : "deleted"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment