Proxies to the real Tire methods? - ruby

I am reading the documentation for the Tire gem and I am a confused about what it mean by the following paragraphs. Could someone explain it?
In fact, all this time you've been using only proxies to the real Tire
methods, which live in the tire class and instance methods of your
model. Only when not trampling on someone's foot — which is the
majority of cases — will Tire bring its methods to the namespace of
your class.
So, instead of writing Article.search, you could write
Article.tire.search, and instead of #article.update_index you could
write #article.tire.update_index, to be on the safe side. Let's have a
look on an example with the mapping method:

It means just what it says: Tire tries hard not to drag methods into your model/namespace, and defines its methods only when they don't exist.
As a regular user, you don't have to care about it much. Whenever you call MyModel.search or MyModel.mapping you can also call MyModel.tire.search or MyModel.tire.mapping.

to piggy back off what Karmi has said, you might find this useful if for example your Model already has a search defined on it.
So if say, Post.search already does something in your rails app, you can just use Post.tire.search to do a tire search instead. I like to use it to signal to all developers who might work in the code after I do, that this is a tire method, so they (hopefully) don't spend time wondering where to find a search method in the Post model.

Related

Understanding ".with" in Ruby

Sorry this is probably a question that has been asked many times but as it regards what is a very common word in English it is pretty much impossible to google or search for it.
I have seen a few examples of Ruby code which looks like this:
EnquiryNotification.with(post: #post)
I'm trying to understand what the ".with" part does. Can anyone shed some light on this please?
with is a class method defined on the EnquiryNotification class (or one of its ancestors). The method is neither a keyword in the Ruby language nor is it a common method on classes shipped with Ruby itself or its standard library. As such, to find what this method does, you would likely have to consult the documentation of your chosen framework or application.
An example of a with method defined in a framework is Sequel::Dataset#with to add a CTE to the current query. The method is also available as a class method in Sequel model classes.
It could also be part of ActionMailer as mentioned by Stefan in a comment above.
In any case though, make sure to consult the documentation of your chosen framework or library for details.

Is there a common convension to put new methods(on top or on bottom)?

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.

laravel 4 api documentation - how to quickly find functions?

I am having trouble in using documentation. Lets say I want to see the source of function
DB::transaction();
I go to http://laravel.com/api/index.html
and enter in the search form 'transaction'
Nothing is found.
I then try to go on the left to Namespaces/Database which makes sense.
And later I have no idea where to go. There is some namespaces, some classes, some interfaces. Later found out that this is in the connection class, which at first I did not even look at. Connection associates to connecting to the database, not making transaction.
And there often happens when I don't know how to quickly find things.
How do you deal with that?
I assume the documentation should be one of best developers friends, but I guess I found this function by using sublime massive search in all files.
Btw also - I lowed the Codeigniter documentation, so thats why also I am disapointed. In codeigniter everythign looked so simple and search worked very well. Typing same word 'transaction' finds like charm.
Ok, tried same way as CI does to serch:
transaction site:http://laravel.com/api/
then it finds. If there is no other way, maybe I should bookmark the search link and just change the keyword or something like that.
CodeIgniter was definitely simpler, to the point that any larger project suffered greatly under the weight of (forcibly) badly misplaced code. Laravel raises the bar there a little bit, but it's to your benefit as a developer (I promise :D ).
Firstly, kudos for searching through the code. Many people do not. You learn a LOT by looking in there.
Laravel Code
For Laravel, you'll do best by knowing about Namespaces, and how they relate to autoloading files (Namespaces will relate to directories, essentially). You likely know this, but it relates to how you can find classes and their methods.
Now, this doesn't go towards knowing where anything is - that comes with some digging into the code yourself. I almost always have Github open to the laravel/framework repository to look at code.
Note: That API search looks for files, rather than methods within them (unfortunately).
Github
As mentioned, I use Github mercilessly for searching code, instead of the API documentation. The search in Github is quite good - it will search within the current repository.
For example, I searched "function transaction" in github and got good results.
It led me to see here that it accepts a closure, and surrounds the code run within the closure around a transaction. You can see that throwing any exception within that closure will get caught and cancel the transaction (and gives you a way to control it).
Facades
As #matit pointed out, Facades do in fact hide where code is. That's a tricky part. In general, you can call the getFacadeRoot() method on any facade to figure out what class it is:
// Figure out what underlying class the Auth facade actually is
echo get_class( Auth::getFacadeRoot() );
Eventually you'll discover patterns in the code. Most facades point towards certain types of classes within each package (For instance, a Manager class who's job it is to decide which underlying implementation is used).
I really suggest reading Taylor's book which goes into the general architecture of Laravel. It's a quick read which is highly worth it.
Where CodeIgniter excelled in simplicity, Laravel excels in teaching you better coding concepts. Give it some time :D (Or use CodeIgniter still, that's cool too - whatever gets your work done!)
This is why I strongly suggest using CTAGS! I use sublime text 2 with the CTAGS plugin. I just press CTRL+SHIFT+Click on the class method and it will bring up a list of classes that have that method, or if only one exists, take me directly to the file and method. It beats searching the API/docs in terms of speed. There is even a Sublime text 2 plugin for Laravel Facades !
https://github.com/stidges/Laravel-Facades-for-ST

ActiveResource + Caching

I'm building an application that consumes models through an api with ActiveResource. I noticed that the
#resource ||= #resource.do a query
doesn't work, i.e. If I put something like that in my controller, my application will still query the api. So there is no built in caching that I'm used to with ActiveRecord. Time to expand my knowledge and skill base, ok.
I found this: http://injectisforwizards.com/blog/read-through-caching-of-activeresource/, and while I don't understand this 100% yet, for controller based queries that do .find, this appears to work. But not for any custom queries I have e.g.:
#current_resource ||= Resource.get(:resource_all, :by_account=>#current_account.account_key)
(which hits a custom controller and runs a scope, returning a collection)
I'm working through this and I'll find out what is going, but I'm curious if someone could tell me simpler terms what is going on, what I can do to smooth over caching in ActiveResource to be more like ActiveRecord, how I can tailor this to cache all queries, etc. Anything really would be helpful.
EDIT:
I found this: https://github.com/Ahsizara/cached_resource which looks promising but it is new (and built off that link above)....notable is that it does not seem to handle any sort of collections, but for one resource finds/caches well.
Since you receive a new instance of a controller for each request, caching like that is not going to work. I'm presuming you have something like this:
def show
#resource ||= expensive_request
end
What are you expecting #resource to be when that method executes? The result of something from a previous call to show? Not going to happen.
What you need to do is put things into Rails.cache if you want them to persist between requests. If you use memcached as a back end, this can be very efficient. See the Caching with Rails guide for more information around section 2.5.
In general, a better approach than the ||= method of caching is to define protected methods that are wrapped with memoize to save the results. For example:
def load_resource
expensive_request
end
memoize :load_resource
Remember that this will only apply to subsequent calls to that method within the context of the same request and is not the same as using Rails.cache.

Ruby: slow down evaluation

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.

Resources