I have a wonderful question, that I'm sure someone has come across before.
I have some classes that are inheriting from ApplicationRecord and ApplicationRecord inherits from ActiveRecord::Base.
Lets call my classes Post, Comment, Author.
Now I have multiple concerns for each of these things which have inclusions. So that I do not have to hard code in each of the concerns I have a ConcernDirectory.
The call to it essentially runs each of the concerns for the model.
ConcernDirectory.inclusions(self).each{ |inclusion| include inclusion }
If I have this in each model everything works fine.
However if I put this into the parent (ApplicationRecord) it no longer works.
When I run it in ApplicationRecord, self points to ApplicationRecord(abstract). How do I get the call from ApplicationRecord to refer to the child from which the call came?
eg.
post = Post.new
when it instantiates its parent class's
--------------.is_a?(::Post)
would be true from the ApplicationRecord.
What is -----------?
Thanks for the help!
Related
I want to use concerns app/controllers/concerns/likeable.rb and app/models/concerns/likeable.rb.
The first one goes to controllers and the second one goes to models.
If I create two files, only the first one is loaded.
What's the best way to solve this problem?
I didn't find a way to use controller and model concerns with the same name without any namespaces.
So, my final solution is to use LikeableModel and LikeableController concerns.
I had the same problem but I was able to resolve it by namespacing the controller and model concerns. I moved all model concerns to app/models/concerns/models/ and all controller concerns to app/controllers/concerns/controllers/. With this, it's possible to have model and controller concerns with the same name.
app/models/concerns/models/likeable.rb
module Models::Likeable
end
app/controllers/concerns/controllers/likeable.rb
module Controllers::Likeable
end
The concerns can be included like this;
class Post < ActiveRecord::Base
include Models::Likeable
end
class PostsController < ApplicationController
include Controllers::Likeable
end
Older question, but I thought I'd throw in another option that I believe fits in with Rails conventions a little neater. The Likeable namespace is responsible for dealing with any items that are likeable, and there are controllers that need to deal with building responses for likeable resources, and models for those likeable resources. Both of these can implement aspects of the Likeable concept. What is needed is a breakdown within that namespace of the different responsibilities.
What I would do in this case is create a file in app/controllers/concerns/likeable/respondable.rb that implements the Likeable::Respondable functionality that a Controller provides. (You may find a better name than Respondable for your needs - for instance, if the controller concern only really handles some logic around params, you may call it Likeable::Paramable, etc.)
Similarly, if the model side of your Likeable scaffold has to do mainly with persistence logic, you might define a Likeable::Persistable module in app/models/concerns/likeable/persistable.rb.
In this way, you can still keep all your logic for likeables in a single namespace, and get more specific for your controller and model concerns.
What's nice about this approach is that you can easily add to the namespace later if you find a need for, say, a utility module or class that needs to live in the lib directory for dealing with special calculations or other shared functionality. In that case, you could easily define a Likeable::Utils module in lib/likeable/utils.rb, or something similar depending on the need, and everything will live under that one, consistent namespace.
You can disttingush two concerns with same name using namespace
Following is example
app/controllers/concerns/like/likeable.rb
module Like
class Likeable
# do some stuff here
end
end
app/models/concerns/likeable.rb
class Likeable
# do some stuff here
end
I've written a module that acts as an abstract interface. I want to use it as a mixin for an ActiveRecord model in a rails app. I'm finding that if I mix it in, the abstract methods are effectively overloading the ActiveRecord::Base methods. For instance, accessors for database-backed attributes and methods like save are no longer defined as ActiveRecord::Base set them up originally.
What is the best way to get around this? My first thought is to somehow mix in ActiveRecord::Base after mixing in my abstract interface module, but I don't know if this is possible or has side effects.
beginner at Rails here.
Can you please help me wrap my head around the theory behind the very, tippy, top portion of most code samples that I see? 'The ActiveRecord::Base', 'Application Controller', & 'ActionController::Base' portions?
What would you call these three? Are they all objects? Classes?
I understand 'class X < ActiveRecord::Base' is to create an object in the Model, & that 'class ApplicationController < ActionController::Base' to create an object in the Controller... so is there something similar for creating an object in the View, just to round it off on all three components of MVC?
ActiveRecord::Base, ApplicationController and ActionController::Base are all classes. You would need to create an instance one of those to get an object, but you'll never do that. Instead you'll extend them to create new subclasses then create instances of those.
I believe there is a base class for views, but you should never see it under normal usage. Typically you'll be creating view templates rather than view classes, so you won't be dealing with Ruby classes in that section of the framework.
To add to what's already been said, as it's all accurate.
I understand 'class X < ActiveRecord::Base' is to create an object in the Model, & that 'class ApplicationController < ActionController::Base' to create an object in the Controller... so is there something similar for creating an object in the View, just to round it off on all three components of MVC?
This is down the right path, but there are some semantic differences.
class User < ActiveRecord::Base merely creates a subclass of ActiveRecord::Base. Until you do something like User.create() do you get an instance of that class, which may sometimes be referred to as an object.
A subclass is a special word for a class that has a parent. In ruby, you may remember classes are, quite confusingly, all subclasses of the Object class.
Also, subclassing ActiveRecord::Base shouldn't be thought of as creating an object in the Model. Instead, consider your subclass as a description of a model (which is generally some data that you wish to store). Every subclass is a model itself. It's all semantics, but it may help your understanding.
The same goes with the controller. You're not creating an object in the controller, instead you're creating a brand new description of a controller. That description isn't really concrete until it gets instantiated, which with rails happens automagically when you or a user request a page from the application.
Finally, there is indeed a class to round out the trio called ActionView::Base. Rails creates it automatically with a call to render in your controller.
ActiveRecord::Base ,ActionController::Base ,are the MVC based classes. However, you can create model or controller without extending those classes, then they will not having the features that provided by the classes.
however,in the view, commonly, there is no one to create object or model in the view. This can ensure to increase the readability and maintainability of your code. It will show more clean code. Besides, in the particular View like index.rb , it is actually connected with the controller,which you able to get the object instance that you initialize in the controller and use it to display your data in the view.
ActiveRecord::Base has a big ol' API with multiple methods for both finding and saving objects. For example, your AR::B objects might have been instantiated from a number of methods:
Foo.new(…)
Foo.create(…)
Foo.find(…)
Foo.find_by_sql(…)
Foo.find_[all_]by_*(…)
bar.foos (associations)
…and finder methods on associations, of course
Similarly, the object in question might get persisted by a few different methods:
foo.create or foo.create!
foo.save or foo.save!
foo.update_attributes or foo.update_attributes!
Now, when writing unit tests, it's good practice to stub external method calls so that your test can focus on the business logic of the method in question. However, when it comes to working with AR::B objects – for example in controller unit tests – it seems like you have to commit to one of the above methods, when actually as far as the business logic of the method is concerned it shouldn't be important which you choose.
Do you have to couple the behaviour of your method this tightly with its implementation or am I missing something simple?
One approach is to build your classes in such a way that you wrap up any ActiveRecord::Base method calls in your own methods.
So instead of calling Foo.new(…) directly...
class Foo < ActiveRecord::Base
def self.create_object(…)
new(…)
end
end
That way in your tests you can stub out your own methods instead of ActiveRecord's.
This approach (including its' benefits) is outlined in detail by Avdi Grimm in the book 'Objects On Rails'... http://objectsonrails.com
I'm factoring out the meat of an ActiveRecord class A into a module M, so that I'm able to duplicate certain data pipelines. The original A had AR macro methods such as belongs_to :X. Although I'm able to separate out non-AR things fine into the module and mix it back into A, the module does not know anything about belongs_to or B out of the box. How do I make those available to the module, and then mix it back into the new shallow A, which only includes M now, and B, which is a clone of A with its own underlying AR table? Or should I write something like an acts_as plugin (right?) instead of M? Retaining belongs_to in A and duplicating it in B works, but defeats the DRY...
When to create a module and when to use inheritance?
A question came up today that got me thinking about how much Ruby on Rails developers really understand about the tools they use.
The question related to refactoring two models that shared functionality. A common enough requirement and a very sensible thing to want to do but the comments and solutions raised my eyebrows some what.
This was the question, somewhat edited and reformatted to make it clearer
I'm factoring out the meat of an ActiveRecord class A into a module M,
so that I'm able to duplicate certain data pipelines.
The original A model had ActiveRecord macro methods such as belongs_to
:X.
Although I'm able to separate out non-AR things fine into the module
and mix it back into A, the module does not know anything about
belongs_to or anything about AR model B out of the box.
How do I make those available to the module, and then mix it back into
the new shallow A, which only includes M now, and B, which is a clone
of A with its own underlying AR table? Or should I write something
like an acts_as plugin (right?) instead of M? Retaining belongs_to in
A and duplicating it in B works, but defeats the DRY principle
What I didn't understand was why the person asking the question was putting this code into a module instead of into a class that the models could descend from.
In Rails (almost) every class descends from another class right?
You see code like
class MyModel < ActiveRecord::Base
all over the place. Fine that ::Base might seem a little mysterious and I can see how that kind of hides what is going on here so lets look at the controller example
All controllers descend from ApplicationController when first generated right?
So you get
class MyController < ApplicationController
How many of you put code into the application controller like before filters and current)user methods and end up using that code in your controllers and views?
Once you take time to think about it a bit then you can see that if you put code in ApplicationController that is public or protected then all controllers that descend from ApplicationController get that functionality right?
ApplicationController is just a class that descends from ActionController::Base the definition looks like this
class ApplicationController < ActionController::Base
Now that looks so familiar the above usage is so common that I start to think that a lot of Rails developers struggle to see the wood for the trees.
This is all about inheritance.
Rails puts a bunch of methods into the ActionController::Base and ActiveRecord::Base classes (That's all they are, classes inside a module) so you can descend your own classes from these classes thereby inheriting the methods and functionality provided by these base classes.
So why not create an abstract ActiveRecord::Base class to solve the problem. This seemed to me the most totally obvious and natural approach to take.
I came up with this solution
In a_base_class.rb
class ABaseClass < ActiveRecord::Base
abstract true
has_many :whatevers
belongs_to :whatevers
def common_methods
#some code here
end
end
Then class a
class A < ABaseClass
# Whatever
end
This could be placed inside a module for namespacing purposes
If you want to put that in a module then descend from WhateverModule::ABaseClass then that's a cool way of name spacing the new base class so that class names don't conflict and that is one of the main purposes of using a module. To name space classes.
Obviously use whatever real class names that make sense to you.
#Rishav Rastogi provided a great answer for using modules and this is what got mne really wondering why thwe solution was not so clear to others and why the question had even been asked in the first place and I started to get the impression that people don't really know what code like this really does
class SomeController < ApplicationController
and
class MyModel < ActiveRecord::Base
When this is stuff that Rails developers use every day?
It's all about inheritance.
Abstract and non abstract classes all inherit from a single class right? The class being inherited from may well inherit from a number of other classes forming a single inheritance chain but it's still single inheritance. each class only descends from one other class.
So what can modules do to help?
Modules are somewhat confusingly used for 2 purposes.
1) To name space things as already mentioned
2) To provide a multiple inheritance scenario. Multiple inheritance is a dirty word in the development world. Things can end up in a right mess but modules provide quite a neat solution.
An example of why you would want multiple inheritance
ActiveRecord::Base provides methods like find_by_something and find.all that return an array of ActiveRecord::Base objects (classes are the code objects are actual things)
Knowing this it would make sense to have the Base class inherit from the array class, but if it did that then it wouldn't be able to inherit from any other more appropriate class. The solution is to mix in a module. If the module contains the array class you get all the juice of array functionality such as .each and .empty? plus all the juice of the other classes that ActiveRecord::Base uses.
So when to use a module and when to inheritance?
Use a module for name spacing (classes can live inside a module)
Use a class for inheritance
So use them both together at the same time unless you want multiple inheritance in which case just use modules
Basically belongs_to is a class method. so you can always. You can write a acts_as plugin as well
module ActiveRecord
module Acts
module M
def self.included(base)
base.extend M::ClassMethods
end
module ClassMethods
def acts_as_m
class_eval <<-CLASS_METHODS
belongs_to :X
CLASS_METHODS
end
end
end
end
ActiveRecord::Base.send(:include, ActiveRecord::Acts::M)
class A
acts_as_m
end
Its generally just about running class_eval