I'm interested in simply slowing down the evaluation of ruby code. Of course I know about using sleep(), but that does not solve my problem.
Rather, I want to slow down every single object instantiation and destruction that happens in the VM.
Why? So I can learn about how particular procedures in ruby work by watching them being carried out. I recently learned about ObjectSpace and the ability to see/inspect all the objects currently living in a Ruby VM. It seems that building a simple realtime display of the objects and properties of those objects within the ObjectSpace and then slowing down the evaluation would achieve this.
I realize there may be ways of viewing in realtime more detailed logs of what is happening inside the ruby process, including many procedures that are implemented at low-level, below the level of actual ruby code. But I think simply seeing the creation and destruction of objects and their properties in realtime would be more edifying and easier to follow.
You could be interested in the answer to this question: getting in-out from ruby methods
With small edits to the code reported there, you could add a sleep to each method call and follow the code execution.
If you want to output some information every time an object is instantiated, you could do that by overriding Class#new. Here's an example:
class Class
alias old_new new
def new(*args)
puts "Creating: #{self.inspect}"
sleep 0.1
old_new(*args)
end
end
class Point
end
class Circle
end
The alias old_new new line creates a backup new method, so we can have the old behaviour. Then, we override the new method and put some code to inspect the subject class and sleep for just a bit for the sake of better readability. Now, if you invoke Point.new, you'll see "Creating: Point". Circle.new will display a "Creating: Circle" and so on. Any objects that are created will be logged, or at least their classes, with a small delay.
The example is a modified version of the one from here.
As for destruction of objects, I'm not sure if there's a sensible way to do it. You could try to override some method in the GC module, but garbage collection is only initiated when it's necessary (as far as I'm aware), so you could easily play with ruby for a while without it ever happening. It probably wouldn't be very useful anyway.
I think the problem is not that ruby is too fast.
In your case you should use some software architecture, for example Model-View-Controller.
It could be in this way. In View you can show options at which speed the Controller should show information for you or you're able to slow down or increase the speed of showing information. Then Controller evaluate small steps (calling methods in Model) and rendered the results of evaluation in the View.
The View is not always the browser or window application, it could be also just a simple terminal.
Related
I very, very rarely have to use the Call Hierarchy window in Visual Studio but today is one of those days.
In this case, I need to explore the depths of the method calls within my application from within a specific method. Currently, this method only calls four other methods, but I need to hunt down and inspect all calls, to all subsequent methods within this method.
Supposedly, the best way to do this is to right-click on my method name in my code and click on the View Call Hierarchy option. The problem is that the results in the hierarchy window only show me the list of "Calls to ..." the method. There is no folder containing the "Calls from..." details. Do I need to configure something or run a process to see the calls from within the method?
A couple of notes, most of the methods being called from within this method are to other methods written in the same class. There's a moderate chance that as I explore the call tree, I'm going to run into 20-30 unique code paths and possibly 300-500 total lines of code I need to inspect, and potentially more. I am also only interested in the method calls from within our solution code base. In fact, from within the hierarchy window, the the drop-down solution is set to "My Solution" which is what I want. Last, just to be clear in case this makes a difference, this is a C#, .Net Framework 4.6.2 project.
Why am I only seeing calls to this method, and not the subsequent call from this method. It's my understanding that this tool should be able to do that.
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.
If we omit visibility modifiers(let's say all methods are public), is there any common convension to put new methods in class? I mean if I put them on bottom it's logically correct, because methods are sorted by date. If I put them on top, it's easy to see and compare what methods are added if the class is very long.
Just depends on what you and your team are comfortable with. I usually have method at the top of my class followed by fields. If there are many method that do different thing you are better off organizing them in a new class. Now without seeing any code I'm simply guessing.
No, I don't think there is.
As Kalagen said it's up to you and your team to decide it.
I would keep any methods that share similar functionality together and keep the class definition short.
The short answer in my opinion is no. Coding style might vary depending on the language you are using and the team you are working with. In addition you might have your own preference as well. I tend to add new methods close to methods that are related to it (e.g. if method1 calls method2 then method1 is above method2). Then it is relatively easy to find the method that's being called. On the other hand, most IDEs can find the method with a mouse click.
If you're using version control, you can easily see what methods were added and in which order, so sorting by date is not needed.
And as others have mentioned, keep the class small. Take a look at the Single responsibility principle. If the methods you are adding are not related to the responsibility of the class, extract them and create a new class.
I am making a tactical RPG game in XNA 4.0 and was wondering what the best way to go about "phases" is? What I mean by phases is creating a phase letting the player place his soldiers on the map, creating a phase for the player's turn, and another phase for the enemy's turn.
I was thinking I could create some sort of enum and set the code in the upgrade/draw methods to run accordingly, but I want to make sure this is the best way to go about it first.
Thanks!
Edit: To anaximander below:
I should have mentioned this before, but I already have something implemented in my application that is similar to what you mentioned. Mine is called ScreenManager and Screen but it works exactly in the same way. I think the problem is that I am treating screen, phase, state, etc, to be different things but in reality they are the same thing.
Basically what I really want is a way to manage different "phases" in a single screen. One of my screens called map will basically represent all of the possible maps in the game. This is where the fighting takes place etc. I want to know what is the best way to go about this:
Either creating an enum called FightStage that holds values like
PlacementPhase,PlayerPhase, etc, and then split the Draw and
Update method according to the enum
Or create an external class to manage this.
Sorry for the confusion!
An approach I often take with states or phases is to have a manager class. Essentially, you need a GamePhase object which has Initialise(), Update(), Draw() and Dispose() methods, and possibly Pause() and Resume() as well. Also often worth having is some sort of method to handle the handover. More on that later. Once you have this class, inherit from it to create a class for each phase; SoldierPlacementPhase, MovementPhase, AttackPhase, etc.
Then you have a GamePhaseManager class, which has Initialise(), Update(), Draw() and Dispose() methods, and probably a SetCurrentPhase() method of some kind. You'll also need an Add() method to add states to the manager - it'll need a way to store them. I recommend a Dictionary<> using either an int/enum or string as the key. Your SetCurrentPhase() method will take that key as a parameter.
Basically, what you do is to set up an instance of the GamePhaseManager in your game, and then create and initialise each phase object and add it to the manager. Then your game's update loop will call GamePhaseManager.Update(), which simply calls through to the current state's Update method, passing the parameters along.
Your phases will need some way of telling when it's time for them to end, and some way of handling that. I find that the easiest way is to set up your GamePhase objects, and then have a method like GamePhase.SetNextPhase(GamePhase next) which gives each phase a reference to the one that comes next. Then all they need is a boolean Exiting with a protected setter and a public getter, so that they can set Exiting = true in their Update() when their internal logic decides that phase is over, and then in the GamePhaseManager.Update() you can do this:
public void Update(TimeSpan elapsed)
{
if (CurrentPhase.Exiting)
{
CurrentPhase.HandOver();
CurrentPhase = CurrentPhase.NextPhase;
}
CurrentPhase.Update(elapsed);
}
You'll notice I change phase before the update. That's so that the exiting phase can finish its cycle; you get odd behaviour otherwise. The CurrentPhase.HandOver() method basically gets the current phase to pass on anything the next phase needs to know to carry on from the right point. This is probably done by having it call NextPhase.Resume() internally, passing it any info it needs as parameters. Remember to also set Exiting = false in here, or else it'll keep handing over after only one update loop.
The Draw() methods are handled in the same way - your game loop calls GamePhaseManager.Draw(), which just calls CurrentPhase.Draw(), passing the parameters through.
If you have anything that isn't dependent on phase - the map, for example - you can either have it stored in the GamePhaseManager and call its methods in GamePhaseManager's methods, you can have the phases pass it around and have them call its methods, or you can keep it up at the top level and call it's methods alongsideGamePhaseManager's. It depends how much access the phases need to it.
EDIT
Your edit shows that a fair portion of what's above is known to you, but I'm leaving it there to help anyone who comes across this question in future.
If already you have a manager to handle stages of the game, my immediate instinct would be to nest it. You saw that your game has stages, and built a class to handle them. You have a stage that has its own stages, so why not use the stage-handling code you already wrote? Inherit from your Screen object to have a SubdividedScreen class, or whatever you feel like calling it. This new class is mostly the same as the parent, but it also contains its own instance of the ScreenManager class. Replace the Screen object you're calling map with one of these SubdividedScreen objects, and fill its ScreenManager with Screen instances to represent the various stages (PlacementPhase, PlayerPhase, etc). You might need a few tweaks to the ScreenManager code to make sure the right info can get to the methods that need it, but it's much neater than having a messy Update() method subdivided by switch cases.
So Candy is a really simple library for interacting with Mongo in Ruby.
My poor SQL brain is having a tough time figuring out how I should map out this problem:
There are users, there are things. Each thing was made by one user, but should be accessible to a subset of all users (specified within the thing). Leaving the specification of user out of the way for now, how would I get a list of all things that user X has access to?
class Thing
include Candy::Piece
end
class Things
include Candy::Collection
collects :thing
end
Should I assign the allowed users to a thing like this? (lets just use strings to reference users for now)
t = Thing.new
t.allowed = ['X','Y','Z']
This seems about right to me, which would make me want to do:
Things.find(allowed:'X')
but it's not quite working…
NoMethodError: undefined method ‘call’ for {:allowed=>"X"}:Hash
any ideas?
I'm really sorry I took so long to catch this and respond. This might be too late for your purposes, but:
Candy doesn't implement a find method. This is on purpose: if an object represents a collection, every access is implicitly finding something in that collection. It's the same reason there is no save method. If the mapping is truly transparent, verbs that mean "Do this in the database" shouldn't be necessary.
So to do what you want, you could either just make a new Things object with the scope passed on creation:
x_is_allowed = Things.new(allowed: 'X')
...or you could save a step and do it by class method:
x_is_allowed = Things.allowed('X')
...or you could start with the whole collection and limit it by attribute later:
things = Things.new
x_is_allowed = things.allowed('X')
So... Um. All of those will work. But. I have to warn you that I'm really not happy with the general usability of Candy right now, and of collections and array fields in particular. The biggest problem is accessors: the [] method isn't working like you'd expect, so you end up having to call to_a and refresh and other things that feel sticky and unpleasant.
This needs to be fixed, and I will do so as soon as I finish the driver rewrite (a related project called Crunch). In the short term, Candy is probably best viewed as an experiment for the adventurous, and I can't guarantee it'll save time until the interface is locked down a bit better. I'm sorry about that.