Skip to content

Instantly share code, notes, and snippets.

@GCorbel
Last active December 18, 2015 00:49
Show Gist options
  • Save GCorbel/5699834 to your computer and use it in GitHub Desktop.
Save GCorbel/5699834 to your computer and use it in GitHub Desktop.
My way to use services objects
#in app/roles/
module CollectorRole
def paintings
["Van Gogh"]
end
end
#in app/models/
class Message < Struct.new(:title, :message)
def to_s
title
end
end
#in app/services/
class MessageGeocoder < Struct.new(:message)
extend Service
def call
puts "Geocoding of #{message}"
end
end
#in app/services/
class MessageNotifier < Struct.new(:sender, :receiver, :message)
extend Service
def call
receiver.extend(CollectorRole)
puts "#{sender} send a message to #{receiver} to have information about #{receiver.paintings}"
message = Message.new("Hello", "World")
end
end
#in app/controllers/
sender = User.new("Bob")
receiver = User.new("Arold")
notifier = MessageNotifier.new(sender, receiver)
notifier.call
MessageGeocoder.new(notifier.message).call
# in lib/
module Service
def self.call(*args)
self.new(args).call
end
end
#in app/models
class User < Struct.new(:name, :email)
def to_s
name
end
end
@GCorbel
Copy link
Author

GCorbel commented Jun 3, 2013

This is a simple example of what I do in an rails application. This is PORO but it's easily integrable in a Rails project. The controller call services objects which contains all the logic.

I think it's simpler than the DCI paradigm. It use roles too but in a simpler way. My models can stay only data but the controller is not tyrannized by the context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment