public
Last active

My way to use services objects

  • Download Gist
collector_role.rb
Ruby
1 2 3 4 5 6
#in app/roles/
module CollectorRole
def paintings
["Van Gogh"]
end
end
message.rb
Ruby
1 2 3 4 5 6
#in app/models/
class Message < Struct.new(:title, :message)
def to_s
title
end
end
message_geocoder.rb
Ruby
1 2 3 4 5 6 7 8
#in app/services/
class MessageGeocoder < Struct.new(:message)
extend Service
 
def call
puts "Geocoding of #{message}"
end
end
message_notifier.rb
Ruby
1 2 3 4 5 6 7 8 9 10
#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
messages_controller.rb
Ruby
1 2 3 4 5 6 7
#in app/controllers/
sender = User.new("Bob")
receiver = User.new("Arold")
notifier = MessageNotifier.new(sender, receiver)
notifier.call
 
MessageGeocoder.new(notifier.message).call
service.rb
Ruby
1 2 3 4 5 6
# in lib/
module Service
def self.call(*args)
self.new(args).call
end
end
user.rb
Ruby
1 2 3 4 5 6
#in app/models
class User < Struct.new(:name, :email)
def to_s
name
end
end

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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.