Using Composition in ruby - ruby

I'm new Ruby but been a .net dev for many a year. I want to implement composition within a couple of my model to make sure they are as loosely coupled as possible but have no idea where to start, or if this is really needed and I'm still thinking to much like a .net dev.
Can anyone give me some pointers on where to start.
Cheers
Colin G

Do you mean this sort of thing?
class Engine
attr_reader :horsepower, :litres
end
class Gearbox
attr_reader :manufacturer, :model_no
end
class Car
def initialize(engine, gearbox)
raise "Invalid Engine Object" if !engine.kind_of(Engine)
raise "Invalid Gearbox Object" if !gearbox.kind_of(Gearbox)
#engine = engine
#gearbox = gearbox
end
end
car = Car.new(Engine.new, Gearbox.new)

Ruby is an object-oriented but dynamically typed language. Being a dynamic language, rubyists tend to use reflections and dynamic modifying of the code much more than .net developers. Of course because it's an object-oriented language you can use mostly the same principles as in .net, and you should too, but always look around and see how that same thing could be implemented in a more dynamic way.
For example the ActiveRecord ORM solves composition using a composed_of method that will dynamically add the appropriate fields and properties to your class. I'm not saying that this is the way it should be done (for example DataMapper, which is another ORM for ruby, choose a more "conservative" approach, and so resembles more like (Fluent)NHibernate), it's just an example of how things can be done differently.
Things like AOP, or DI aren't a foreign concept for dynamic languages, they are just usually done in an alternative way. Keep an open mind on the dynamic aspects of the language but don't overdo them.

Related

What is a good practice for dependency injection in Ruby?

I've been reading Sandi Metz's Practical Object-Oriented Design in Ruby and many sites online discussing design in Ruby. Something I've had a hard time fully understanding is the proper way to implement dependency injection.
The internet is flooded with blog posts that explain how dependency injection works in what I think is a very partial way.
I understand that this is supposed to be bad:
class ThisClass
def initialize
#another_class = AnotherClass.new
end
end
While this is a solution:
class ThisClass
def initialize(another_class)
#another_class = another_class
end
end
And that I could send the AnotherClass.new like this:
this_class = ThisClass.new(AnotherClass.new)
That is the approach that Sandi Metz recommends at least. What I don't understand is where should a line like that go? It has to go somewhere and generally in examples of this what's shown is a line like that being placed totally outside of any class, method, or module as if I'm simply entering it all by hand in IRB for testing purposes.
This post (among others) suggests this different approach:
class ThisClass
def another_class
#another_class ||= AnotherClass.new
end
end
Jamis Buck would take a similar approach like this:
class AnotherClass
end
class ThisClass
def another_class_factory(class_name = AnotherClass)
class_name.new
end
end
However, these two examples both preserve AnotherClass's name inside ThisClass, which Sandi Metz says is one of the main things we're trying to avoid.
So what is the best practice for doing this? Should I make a 'dependency' module filled with methods that are factories for objects of each class in my application?
Something I've had a hard time fully understanding is the proper way to implement dependency injection.
I think the best definition of a "proper" implementation is one that adheres to the SOLID principles of object oriented design. In this case mostly the Dependency Inversion Principle.
In this regard, this is the only presented solution that does not violate the DIP(1):
class ThisClass
def initialize(another_class)
#another_class = another_class
end
end
In all other cases, ThisClass has a hard dependency on AnotherClass, and can not function without it. Furthermore, if we wish to replace AnotherClass with a third, we need to modify ThisClass, which is a violation of the Open Closed Principle.
Of course, in the example above, naming the parameter and instance variable another_class is not ideal, since we do not now (and do not need to know) what object is passed to us, as long as it responds to the expected interface. This is the beauty of polymorphism.
Consider the below example, taken from this ThoughtBot video on DIP:
class Copier
def initialize(reader, writer)
#reader = reader
#writer = writer
end
def copy
#writer.write(#reader.read_until_eof)
end
end
Here you can pass any reader and writer objects that respond to read_until_eof and write respectively. This gives you full freedom to compose your business logic using different pairs of read and write implementations, even at runtime:
Copier.new(KeyboardReader.new, Printer.new)
Copier.new(KeyboardReader.new, NetworkPrinter.new)
Which brings us to your next question.
It has to go somewhere and generally in examples of this what's shown is a line like that being placed totally outside of any class, method, or module [...]
You are correct. While object thinking involves modelling the domain with well isolated, decoupled, and composable objects, you will still need to define how these objects interact, in order to implement any business logic. After all, having composable objects is no good unless we compose them.
The analogy that is often made here is to think of your objects as actors. You are the director, and you still need to create a script(2) for the actors to know how to interact with each other.
That is, you need an entry point into your application. A place where the script starts. This might itself be an object--normally an abstract one. In a command line application, it can be your classic Main class, and in a Rails application it can be your controller.
This might seem strange at first, because the focus of object thinking is on modelling concrete domain objects, and a great deal of all writings on the subject is dedicated to this effort, but just remember the actor-script metaphor, and you'll be on your way.
I strongly recommend you pick up the book Object Thinking. It does a great job explaining the mindset behind object oriented design, without which knowing the language specific implementation details becomes rather futile.
(1): It is worth noting that some proponents consider storing an instance of another class in an instance variable an anti-pattern, but in Ruby, this is fairly idiomatic.
(2): I am not sure if this is the origin of the term script in programming in general, but maybe some historian can shed some light on this.

Adopting "Growing Object-Oriented Software" techniques to Ruby on Rails

I read Growing Object-Oriented Software, Guided by Tests by Steve Freeman and Nat Pryce and was impressed very much. I want to adopt the ideas of this book in my Rails projects using RSpec, though its examples are written in Java.
A basic precept of this book is that we should mock interfaces instead of concrete classes. They say we can improve the application design by extracting interfaces and naming them.
But, Ruby doesn't have any syntax equivalent to Java's interface. How can I utilize their techniques for Rails projects?
UPDATE
For example, in the page 126 the authors introduced Auction interface in order to implement the bid method. Firstly, they mocked Auction.class to make the test pass, then they implemented an Auction class as anonymous inner class in the Main class. Finally, they extracted a new concrete class XMPPAuction from Main (page 131-132).
This incremental approach is the crux of this book in my opinion.
How can I adopt or imitate such a series of code transformation in the Ruby development?
Check out this previous Stack Overflow answer for a good explanation of interfaces in ruby.
Also, Practical Object-Oriented Design in Ruby is a book in similar vein as Growing Object Oriented Software book, but with ruby examples. Worth checking it out.
Since in Ruby, all things are duck-typed and the interface is simply the set of fields and methods that are publicly exposed you can do one or more of the following:
Test
Design your tests to test interfaces and name and comment your tests appropriately - then you can pass all of your "concrete implementations" of your "interface" through the same test suite. As long as your test suite covers your application's edge cases anything in your application that takes an instance of any of these concrete classes will be able to handle an instance of any of the other concrete classes.
Use base classes
Define a base class that all of your concrete classes will inherit from where all of the methods throw a NotImplemented error. This gives you a hierarchy that you can visualize - however, it does require extra classes and may encourage numerous is a tests in your production code rather than that code relying on has a.
You're right that Ruby does not have formal interfaces. Instead, interfaces are implicit in the messages that an object handles (see duck typing).
If you are still looking for a more formal way to "enforce" an interface in Ruby, consider writing a suite of automated unit tests that are green if an object conforms to the interface properly, and are red otherwise.
For examples, see ActiveModel::Lint::Tests and rspec's shared examples.

How I can modularize Rails model?

I'm implementing several classes which does not have data by itself, just logics. These classes implements access control policy to date which depends on several parameters taken from data from other models.
I initially try to find answer to "Where to store such classes?" here, and the answer was apps/models directory. That's ok, but I like to clearly separate these classes from ActiveRecord inherited classes in hierarchy, both as file and class.
So, I created classes inside Logic module, like Logic::EvaluationLogic or Logic::PhaseLogic. I also wanted to have constants which passed between these logics. I prefer to place these constants into Logic module too. Thus, I implemented like this:
# in logic/phase_logic.rb
module Logic
PHASE_INITIAL = 0
PHASE_MIDDLE = 1000
class PhaseLogic
def self.some_phase_control_code
end
end
end
# in logic/evaluation_logic.rb
module Logic
class EvaluationLogic
def self.some_other_code
Logic::PhaseLogic.self.some_phase_control_code(Logic::PHASE_INITIAL)
end
end
end
Now, it work just fine with rspec (It passes tests I wrote without issues), but not with development server, since it can't find the Logic::PHASE_INITIAL constant.
I suspect it's related to the mismatch of the autoloading scheme of Rails and what I wanted to do. I tried to tweak rails, but no luck, ended-up with eliminating module Logic wrap.
Now the question I want to ask: How I can organize these classes with Rails?
I'm using 3.2.1 at this moment.
Posted a follow-up question "How I can organize namespace of classes in app/modules with rails?"
I am not sure whether I really understand your classes, but couldn't you create a Logic module or (I would rather do this:) PhaseLogic and EvaluationLogic objects in /lib directory?
It is not said that "Model" is always descendant of ActiveRecord. If the object belongs to "business logic" then it is a model. You can have models which do not touch database in any way. So, if your classes are "business objects", place them in 'app/models' and use like any other model.
Another question is whether you should use inheritance or modules - but I would rather think about including a module in PhaseLogic, and not about defining PhaseLogic in a module. Of course, all this depends heavily on the intended role of your objects.
Because in Ruby the class of object is not important, you do not need to use inheritance. If you want to 'plug' the logic objects into other objects, just take care that all '*Logic' classes have the required methods. I know that all I said is very vague, but I think I cannot give you some more concrete suggestions without knowing more about the role of these objects.
Ah, and one more thing!
If you find yourself fighting with Rails class autoloading, just use the old require "lib/logic.rb" in all the classes where you are using Logic::PHASE_INITIAL constants.
In this case I suppose that your problem was caused by different order of loading. The logic/evaluation_logic.rb has been loaded before logic/phase_logic.rb. The problem may disappear if you create logic.rb somewhere, where class autoloading can find it, and define these constants in that file.
Don't name your classes or modules Logic use specific names. Start with extracting logic into separate classes and then try to break them into smaller ones. Use namespaces to distinguish them from each other in lib folder, after this steps you would be able to extract some logic parts to separate gems and reduce codebase and complexity of application. Also take a look into presenter pattern.

Using mixins vs calling a method directly

I'd like to know when is the best time to use mixins vs calling a method directly.
For example, consider HTTParty. On one of its examples https://github.com/jnunemaker/httparty/blob/master/examples/basic.rb
you can use HTTParty.get('http://twitter.com/statuses/public_timeline.json') or you can create a class that includes HTTParty and then use it as you would calling HTTParty itself.
What's the difference with me just creating something like this:
class Partay
#base_uri = 'http://localhost:3000'
def self.post(endpoint, options)
HTTParty.post(#base_uri + endpoint, options)
end
end
versus the given example:
class Partay
include HTTParty
base_uri 'http://localhost:3000'
end
True that in such a trivial example perhaps using the include would save more characters, but I'd imagine on a much more complicated class it doesn't really make a difference.
A few clarificatory questions:
Would this be related to a composition vs aggregation argument? Is there any design or architecture best practice regarding this? Should I treat mixins as some sort of inheritance and use them as such (inheritance if it's an is-a relationship, composition if it's a has-a relationship, etc.)? Should I only mixin a module if it was intended to be done so (because docs say it expects certain methods from you, like Enumerable) or is it just good practice to do so? Would using a mixin mean a tighter coupling between the module and my class (and is it relatively good or bad in general)?
In the given example, there is not much difference, other than the syntax is much more friendly with the mixin, and could potentially become a DSL that you can use later.
More generally, mixins allow you to use these same functions in different classes without repeating yourself, and without extending another class (mixins are, for example, a way of working around the fact that ruby does not allow multiple inheritance). This favours reuse and goes towards the DRY philosophy dear to the ruby users. As ruby is duck-typed, mixins allows you to take full advantage of polymorphism without inheritance.
Another great advantage of mixins is that they can be added at runtime, so this means you can add behaviour to a class "dynamically".
Update: I personally prefer using modules as mixins, rather than calling methods on it as the methods then become part of your class, which means that they can access the other members of the class. I’m however reluctant to call it a is-a relationship, even though that’s what it is in practice. As the “Well-Grounded Rubyist” says, classes model entities or things (class names tend to be nouns), modules encapsulate properties or characteristics (module names tend to be adjectives).

What separates a Ruby DSL from an ordinary API

What are some defining characteristics of a Ruby DSL that separate it from just a regular API?
When you use an API you instantiate objects and call methods in an imperative manner. On the other hand a good DSL should be declarative, representing rules and relationships in your problem domain, not instructions to be executed. Moreover ideally DSL should be readable and modifiable by somebody who is not a programmer (which is not the case with APIs).
Also please keep in mind the distinction between internal and external DSLs.
Internal domain specific language is embedded in a programming language (eg. Ruby). It's easy to implement, but the structure of the DSL is dependent on the parent language it is embedded in.
External domain specific language is a separate language designed with the particular domain in mind. It gives you a greater flexibility when it comes to syntax, but you have to implement the code to interpret it. It's also more secure, as the person editing domain rules doesn't have access to all the power of the parent language.
DSL (domain specific language) is an over-hyped term. If you are simply using a sub-set of a language (say Ruby), how is it a different language than the original? The answer is, it isn't.
However, if you do some preprocessing of the source text to introduce new syntax or new semantics not found in the core language then you indeed have a new language, which may be domain-specific.
The combination of Ruby's poetry mode and operator overloading does present the possibility of having something that is at the same time legal Ruby syntax and a reasonable DSL.
And the continued aggravation that is XML does show that perhaps the simple DSL built into all those config files wasn't completely misguided..
Creating a DSL:
Adding new methods to the Object class so that you can just call them as if they were built-in language constructs. (see rake)
Creating methods on a custom object or set of objects, and then having script files run the statements in the context of a top-level object. (see capistrano)
API design:
Creating methods on a custom object or set of objects, so the user creates an object to use the methods.
Creating methods as class methods, so that the user prefixes the classname in front of all the methods.
Creating methods as a mixin that users include or extend to use the methods in their custom objects.
So yes, the line is thin between them. It's trivial to turn a custom set of objects into a DSL by adding one method that runs a script file in the right context.
The difference between a DSL and an API to me is that a DSL could be at least understood (and verified) if not written as a sub-language of Ruby by someone in that domain.
For example, you could have financial analysts writing rules for a stock trading application in a Ruby DSL and they would never have to know they were using Ruby.
They are, in fact, the same thing. DSLs are generally implemented via the normal language mechanisms in Ruby, so technically they're all APIs.
However, for people to recognize something as a DSL, it usually ends up adding what look like declarative statements to existing classes. Something like the validators and relationship declarations in ActiveRecord.
class Foo << ActiveRecord::Base
validates_uniqueness_of :name
validates_numericality_of :number, :integer_only => true
end
looks like a DSL, while the following doesn't:
class Foo <<ActiveRecord::BAse
def validate
unless unique? name
errors.add(:name, "must be unique")
end
unless number.to_s.match?(/^[-]?\d$/)
errors.add(:number, "must be an integer")
end
end
end
They're both going to be implemented by normal Ruby code. It's just that one looks like you've got cool new language constructs, while the other seems rather pedestrian (and overly verbose, etc. etc.)

Resources