Ruby: Arranging larger classes/files [closed] - ruby

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm aware that ruby class files should generally be quite small, but sometimes I find logic in classes that (a) don't really warrant their own file, but (b) would be more readable if I could group them somehow.
For example, in certain classes I may have (let's say) 10 methods which determine paths. At the moment, I tend to just throw some a few lines of decorative "### PATHS ###" type comments around them to distinguish them from the rest of the group. I'm wondering if theres a better way(?)
Am I right in thinking implementing subclasses/modules within a class just to improve readability is a little excessive, or do other folks do this? Any other thoughts appreciated.

Maybe they do warrant their own file - Think single responsibility principle. Since you haven't shown us any code, here's an idea for a separate class that handles the paths for an object:
class FooPaths
def initialize(foo)
#foo = foo
end
def path_one
# code to calculate path using #foo
end
def path_two
#code to calculate another path using #foo
end
end
The idea is that your class Foo is probably doing too many things. Create smaller classes which accept #foo in the initializer, and then that smaller class can handle a smaller subset of operations involving Foo. It's also a lot easier to test.

When I have a bunch of similar helper methods, that means one of two things.
I have a business concept (read: object) that needs to be defined
I have a bunch of business concepts that act in a similar way.
For the first case, very often, the first argument passed into the method is the name of the business concept
class User < ActiveRecord::Base
# active record attributes :first_name, :last_name
def self.full_name(first_name, last_name)
[first_name, last_name].compact.join(" ")
end
def self.extract_first_name(full_name)
full_name.split.first
end
end
So I would create a concept for full_name:
class User << ActiveRecord::Base
# active record attributes :first_name, :last_name
def full_name
FullName.from_parts(first_name, last_name)
end
def full_name=(val)
if val
self.first_name, self_last_name = val.partsfirst_name, val.last_name
else
self.first_name = self.last_name = nil
end
end
end
class FullName
attr_accessor :first_name, :last_name
def to_s
parts.join(" ")
end
def parts
[first_name, last_name].compact
end
def eq(other)
to_s.eq(other)
end
def self.from_parts(first_name, last_name)
# [...]
end
def self.from_full_name(full_name)
# [...]
end
end
I know the example is contrived, but I've found that a lot of view logic and helpers groups around this concept. So if you end up finding more concepts that can be brought into this, or you notice that you often pass these around in groups, then it is a great candidate. Also, if you have had a number of conversations with the business users around the full name of a user, then that is really saying that you want a business concept here.
For the second case, it is sometimes the case that you want to add "the same" attribute onto a bunch of disparate business objects. They just happen to be calculated in different ways. The path for a chapter book and a dictionary are different. Introduce the concept of a chapter book and a dictionary, both having the path parameter. As stated above, if you find that you are not using these business concepts often with your users, chances are, this is not the right approach here.

Related

Ruby OOP Class Responsibilities

I am still trying in wrap my head around OOP in Ruby. Let's say I'm trying to create a simple Hangman game and I want to select a random word from a text file. So far I have 2 examples in the codeblock. The first example shows a Word and Game class, where the Word class generates a random word and the Game class calls the Word class in the initialize method. The second example has only a Game class where the Game class itself generates the random word. My question is, is it the Game classes responsibility to generate the random word or use the Word class?
# First Example
module Hangman
class Word
def self.words
File.readlines("../words.txt")
end
def self.random
words.select { |word| word.length > 4 && word.length < 13 }.sample
end
end
class Game
attr_reader :random_word
def initialize
#random_word = Hangman::Word.random
end
end
end
# Second Example
module Hangman
class Game
attr_reader :words, :random_word
def initialize
#words = File.readlines("../words.txt")
#random_word = #words.select { |word| word.length > 4 && word.length < 13 }.sample
end
end
end
Sandi Metz has a great example of how to answer this question in Practical Object Oriented Design in Ruby. Sadly, since it is copyrighted I can't link directly to the passage.
In her example, although a bicycle seems like a good candidate for a class due to its obvious existence in the problem domain, at the point in the development of her application that she needs to compute a gear ratio, she realizes that the inputs to that calculation are all related only to gears: the number of teeth on each of two instances of Gear, and thus places the functionality on Gear, deferring the creation of the Bicycle class until a later time.
So the general answer is: look to the input values for the required computation and place that computation's definition on the class with the greatest number of those input values as fields already.
In your specific case:
is it the Game classes responsibility to generate the random word or use the Word class?
Well first off, it seems like your Word class is more of a WordList class, although depending on your future direction, it could remain a Word class but in embodiment of the composite pattern . If you do keep it as a WordList class, it has no instance methods, so discussing responsibilities of the class becomes very difficult. Effectively the class itself has methods, but the class is always expected to be at "singleton instantiation scope" or a constant. Ruby class names are constants, so defining methods only at the level of constants is effectively procedural, not object-oriented, code.
To make WordList object-oriented, you can pass an IO instance (File is a subclass, but why depend on a subclass whose additionally defined methods are not needed by your code?) to WordList#initialize , potentially providing singleton access with a
def self.singleton_instance
#singleton_instance ||= new(File.open("../words.txt"))
end
This allows other clients to reuse the WordList class in other contexts by providing any kind of IO, including a StringIO, and separates and makes explicit that loading the default, singleton WordList is only one way this class expects to be used, requires the constant-scope level file from the parent directory, and allows the instance-level behavior of a WordList to be defined.
So far it looks like that instance-level behavior you need is a random selection from all the words. Getting back to Sandi Metz's advice, WordList does seem like a good place to put the computation of the random selection, because WordList will have a field:
attr_reader :words
def initialize(io)
#words = io.readlines
end
and it's exactly the words field that the filtration is to be performed upon, so this class is a good candidate for that functionality:
def random # notice no self. prefix
words.select { |word| word.length > 4 && word.length < 13 }.sample
end
and later, to actually-use,
#random_word = Hangman::WordList.singleton_instance.random
This also gives you a place to swap-out the singleton instance for a different one if you need to later, without changing the WordList class. That should score points for complying with the Open Closed Principle too.
(An aside: it seems that "random" may be a poor choice for method name -- it's not just random, but also constrained to a length of between 4 and 13 exclusive. Perhaps "random_suitable_length_word"?)
In general it depends.
For this specific case I think most people would agree that splitting the structure between Word and the Game is a good idea.
Word is a nice small testable piece, and so it does deserve its own class.
It also could be reusable in a number of games that need a random word.
I think this becomes clearer if you rewrite word so it has an initialize method. Then the game is simply calling Word.new(...) to get a new random word.
Imagine if there was a gem called "words" that already did all this. You would be happy add the gem and say done deal. Well that is an easy way to tell you have made a good division of labor, even no such gem exists.
By the way once you think this should be a separate class, you might want to check to see if somebody already did it for you. In this case there is a gem random-word.
What would the parameters be to words initialize? Well the length of the word, skill level, etc etc.
class Word
def self.words
#words ||= File.readlines("../words.txt")
end
def initialize(min_length, max_length)
Word.words.select do |word|
word.length > length && word.length < max_length
end.sample
end
end

Why should I use lambda/proc ?Explain it's importance [duplicate]

This question already has answers here:
When to use lambda, when to use Proc.new?
(14 answers)
Closed 8 years ago.
I am new to ruby, and while learning it I didn't understand the concept of lambdas or procs. I know lambda and proc are the blocks of code that have been bound to a set of local variables. But I don't understand their use.
So
what advantage does a programmer get from it?
I had asked this question in past and got marked as duplicate and was given a link that had totally unrelated answered so please before marking it as duplicate or scolding me please view the answers of other links by yourself first.
This is a broad question. You're basically asking "why are closures important?". Two uses that come to mind for me are:
DISCLAIMER: I haven't actually run any of this code, but it should get the point across.
Delayed execution of code. If I want to pass some code as a callback (e.g. Rails' after_create), I can use a closure to "hook" into Rails by passing a block. That block has the context of the current class, but it doesn't need to get run until Rails says so.
class SuperClass
def self.after_create(&block)
#__after_create = block
end
def self.create
# do normal create logic
instance = self.new
if #__after_create
#__after_create.call(instance)
end
end
end
class MyClass < SuperClass
after_create {|instance| instance.log}
def log
puts 'hello world!'
end
end
MyClass.create
Passing functions as parameters. This makes it easier to do things like write a generic tree traversal algorithm that just passes each node of the tree to some function:
def Tree.elements
["hello", "world!"]
end
def Tree.traverse(&block)
elements.each {|el| block.call(el)}
end
Tree.traverse {|el| puts el} # "hello" "world!"
Tree.traverse {|el| puts el.size} # "5" "6"

Mocking User Interface with RSpec Ruby [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've been looking on google for an answer but I can't seem to find the right answer.
Basically I want to test out different User Interfaces(Console) in my engine. I was told to use Mock Classes, and I can't find a straight answer anywhere.
Edit:
Would this be a good way to mock a class(UI)
class UiMock
def initialize
#player_one = true
#player_two = true
#board = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
end
def set_move(mark, index)
#move_set = true
#board[(index.to_i) - 1] = mark
end
Test would be something like this
ui = UiMock.new
game = Game.new(ui)
it "creates a game" do
game.player_one.should be_true
game.player_two.should be_true
end
it "sets a move" do
game.set_move("X", 5)
ui.move_set.should be_true
end
The simplest mock object might literally be:
mock_ui = Object.new
game = Game.new( mock_ui )
# Now run your test
Normally you will need the mock to respond to methods that the Game class uses. If you provide an example of one method of the Game class that you need to test, and which methods of the real UI class that it calls, I could extend this answer to show how that might work.
It is not clear whether you are being asked to write a full emulation of a known ui class, or something simpler and tighter for specific tests. Full emulations for mocks are used less often, because they take a lot of effort to write, but the advantage is that the tests become less sensitive to changes in implementation. For example you could write a mock memcached service using hashes, and almost completely replicate the interface to Memcached class (the functionality you would lose is cross-process caching, usually not something you'd test - at least not in a unit test).
I think you current mock and test could be streamlined a little, as there is code that doesn't seem to be testing anything (yet)
class UiMock
attr_reader :move_set
def set_move(mark, index)
#move_set = true
end
end
Test:
ui = UiMock.new
game = Game.new(ui)
it "sets a move" do
game.set_move("X", 5)
ui.move_set.should be_true
end
the reason for removing some of the code is that it was not clear whether or not it was needed. Maybe you will need to represent the board and players in your mock UI, but so far the test assertions you have written don't require it. It is advisable to build these up over time as your test and code require them (even alternating between adding one or two tests and adding matching features - just enough on each part to show what needs to be coded next), unless you already have a very clear picture in your head on how all the code will fit together at the end.
Note that mocha has a simple pattern for the above test:
require 'mocha'
ui = Object.new
game = Game.new(ui)
it "sets a move" do
ui.expects( :set_move )
game.set_move("X", 5)
end
I think you're looking for Aruba, an extension of cucumber.
Also this page is a great resource for all-things command-line.

Is type conversion possible with inheritance in Ruby?

I'm using Ruby, and writing classes with inheritance.
For example:
class Canine
def initialize
end
def make_noise
puts "whoosh whoosh"
end
end
class Dog < Canine
def initialize
end
def make_noise
puts "wong wong"
super
end
end
Now I have a dog object:
jack = Dog.new
Is it possible to call the make_noise() method of Canine through the dog object?
In other languages it would be a typecast, something like:
(Canine)jack.make_noise
Note this is not Ruby syntax, hence, my question.
Is it possible to do this in Ruby? And if so, how?
You can do something like this:
Canine.instance_method(:make_noise).bind(jack).call
A better plan would be to just give the method in the super class an alias, or rename it.
Ruby does not allow casting or conversion in this fashion, at least not in the conventional sense. This is rarely necessary anyway, since Ruby is based on duck typing and not a rigid type system.
Are you expecting "whoosh whoosh" from the call? That's something that would only happen with non-virtual methods in a more strictly typed language like C++. It goes against proper object oriented design.
If you explore the design patterns employed in object-oriented design, you can always solve this sort of problem another way.
What you might want here is a presenter to handle the make_noise functionality.
Otherwise you'll need to write a to_canine method that can convert to the base type, though it's still not clear why you'd need such a thing.
You can do it like this:
d = Dog.new
d.class.superclass.instance_method(:make_noise).bind(d).call
or
Canine.instance_method(:make_noise).bind(d).call
. . . not pretty! I'm not sure if there's a better way
Edit: I think I agree with other answers here, in that Ruby's approach to OO will give you access to other patterns that achieve whatever goals this construct might help you with (perhaps in other languages). I don't see this kind of class/superclass method munging in practice on projects I have been involved in.
I am not sure why you need this, depending on needs it may be done totally differently, but with limited knowledge I would suggest this
class Dog < Canine
def initialize
end
def make_noise only_parent=false
puts "wong wong" if !only_parent
super
end
end
or
class Dog < Canine
def initialize
end
alias :make_super_noise :make_noise
def make_noise
puts "whoosh whoosh"
super
end
end

Does this look right as Ruby's duck typing?

I created a program that tracks car mileage and service history in order to update the user for upcoming service needs for the car.
I have three classes: Car, CarHistory, and CarServiceHistoryEntry. The third one is straightforward; it holds all the attributes associated with a service: date, mileage, service performed, etc. The CarHistory class is as follows:
require_relative 'car_service_history_entry'
class CarHistory
attr_reader :entries
def initialize (*entry)
if entry.size > 1
#entries = []
else
#entries = entry
end
end
def add_service_entry entry
#entries << entry
end
def to_s
entries_string = ""
#entries.each {|entry| entries_string << "#{entry.to_s}\n"}
entries_string
end
end
In initialize, should the class of entry be checked?
In add_service_entry, adopting duck typing (as in Andy Thomas's argument in "Programming Ruby"), would I even test if a CarServiceHistoryEntry could be added? Couldn't I just pass a String instead of setting up and then adding CarServiceHistoryEntry in my unit testing?
Since the only necessary attributes of a CarHistory are the entries array and the to_s method, should I just scrap this class all together and put it into the car class?
For 1 and 2, you need to release your tight grip on "strict-typing" when you move to a loose-typed language like Ruby.
Should you check your input arguments ? The traditional answer would be yes. An alternative way would be to have good names and unit tests that document and specify how the type is supposed to work. If it works with other types, fine.. that's an added bonus. So if you pass in an incompatible type, it would blow up with an exception, which is good enough in most-cases. Try it out and see how it feels (possible outcomes: Liberating / "Retreat!". But give it a fair try.). Exceptions would be if you're designing public APIs for shared libraries - in which the rules are different. You need to fail fast and informatively for bad-input.
As for clubbing car_history into car - I'd ask what the responsibilities of your Car class are. If maintaining its own history is one of them, you could club them. In the future, if you find a lot of methods creeping in related to car history, you could again reverse this decision and extract the CarHistory type again. Use the SingleResponsibilityPrinciple to make an informed decision. This is just OOP - Ruby doesn't degrade object design.
Code Snippet: the code can be more concise
# just for simplicity, I'm making HistoryEntry a string, it could be a custom type too
class CarServiceHistoryEntry << String
end
class CarHistory
attr_reader :entries
def initialize(*history_entries)
#entries = history_entries
end
def add_service_entry(entry)
#entries << entry
end
def to_s
#entries.join("\n")
end
end
irb>x = CarHistory.new("May 01 Overhaul", "May 30 minor repairs")
irb>x.add_service_entry("June 12 Cracked windshield")
irb>x.to_s
=> "May 01 Overhaul\nMay 30 minor repairs\nJune 12 Cracked windshield"
It's hard to comment on the relationship of the CarHistory class to your others, but I'm sure it will become clear to you as you go along.
A couple of your methods could be simplified, although I must say I didn't understand the if in initialize, perhaps it was just backwards and should have been > 0.
def initialize *entry
#entries = entry # if not specified it will be [] anyway
end
def to_s
#entries.join "\n"
end
And yes, Ruby should be simple. You don't need to litter your code with runtime type checks. If the code runs your unit tests then you can just declare victory. The zillions of explicit conversions tend to patch up type errors anyway.
Ruby is going to check your types at run-time anyway. It's perfectly reasonable to leave the type checking to the interpreter and put your effort into functional tests.
I'll skip the first two questions and answer the third. If the only attribute of a CarServiceHistoryEntry is a string, then yes, scrap CarHistory (as well as CarServiceHistoryEntry) and add a service_history attribute to Car which would just be an array of strings. Until proven otherwise, simpler is better.
As to duck typing, you would never want to test if something 'is a' only see if it 'responds to' (at most).
Finally, to answer question #1, no its supposed to be even simpler :)
Hope this helps,
Brian

Resources