Created
April 4, 2018 17:33
-
-
Save kopylovvlad/ac52fc1f06e15beb795092b454506dd8 to your computer and use it in GitHub Desktop.
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
module Visitable | |
def accept(visitor) | |
raise 'does not implement error' | |
end | |
end | |
# class that accept any visitor | |
class User < ApplicationRecord | |
include Visitable | |
# some code | |
def accept(visitor) | |
visitor.visit_user(self) | |
end | |
end | |
# class that accept any visitor | |
class Order < ApplicationRecord | |
include Visitable | |
# some code | |
def accept(visitor) | |
visitor.visit_order(self) | |
end | |
end | |
# main class for any visitors | |
class AbstractVisitor | |
def visit_user(user) | |
raise 'does not implement error' | |
end | |
def visit_order(order) | |
raise 'does not implement error' | |
end | |
# here we can add some method for any classes | |
end | |
class XMLExportVisitor < AbstractVisitor | |
def visit_user(user) | |
# export logic user to XML is here | |
end | |
def visit_order(order) | |
# export logic order to XML is here | |
end | |
end | |
class JSONExportVisitor < AbstractVisitor | |
def visit_user(user) | |
# export logic user to JSON is here | |
end | |
def visit_order(order) | |
# export logic order to JSON is here | |
end | |
end | |
# and controller in rails-app | |
module Api | |
module Users | |
class ExportsController < ApplicationController | |
before_action :find_user | |
def xml_export | |
@report = @user.accept(XMLExportVisitor.new) | |
end | |
def json_export | |
@report = @user.accept(JSONExportVisitor.new) | |
end | |
private | |
def find_user | |
@user = User.find(params[:id]) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment