Factoring out belongs_to into a common module - ruby-on-rails

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

Related

Run class evaluation from Application Record?

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!

How to use two concerns with the same name?

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

What are before_create, validates_presence_of, has_many etc?

I understand what these statements do, but not how to refer to them. They exist within a class, outside of that class's methods and perform a variety of functions.
Collectively, what are they called?
These methods are really just class methods. Try this:
class Test
def self.before_create
puts "before_create"
end
before_create
end
The specific use case you mentioned - Rails DSL methods such as before_create, that are only available inside a class body — are often called class macros. Rubys metaprogramming abilities give you multiple ways to build them. A simple one is to make them private:
module Foo
private
def before_create
puts "before_create"
end
end
class Bar
extend Foo
before_create
end
before_create is now accessible inside the class body, but not from outside:
Bar.before_create
NoMethodError: private method `before_create' called for Bar:Class
In pure Ruby terms, they are all just method calls.
However, they do have a common theme. In the way they are constructed and used, you could consider them part of a Domain-Specific Language (DSL) - the ones you list are part of Active Record's DSL for creating data models.
Ruby lends itself well to creating DSL-like mini languages, using mix-ins or a base class in order to provide a set of class methods, which in turn will store data or create methods on the class and instances of it using meta-programming techniques.

Possible to mixin ActiveRecord::Base instead of inheriting in Ruby on Rails?

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.

How do you stub ActiveRecord::Base methods without making assumptions about how it's used?

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

Resources