Rails/Ruby Mixin brings unwanted other class methods - ruby-on-rails

Just hoping someone can explain this for me..
I have a Site class that imports a module:
Site
class Site < ActiveRecord::Base
include TrackableChanges
...
In trackable_changes.rb
I have this code..
module TrackableChanges
include ActiveSupport::Callbacks
def self.included(base)
# Initialize module.
base.has_many :change_requests, :as => :model, :dependent => :destroy
#Callbacks
base.before_save :before_save_change_request
base.after_save :after_save_change_request
base.before_destroy :before_destroy_change_request
Facility
end
...
The reference to Facility is really confusing me (I put a trivial reference in here..). Basically in Facility.rb I have this..
class Facility < ActiveRecord::Base
acts_as_citier
acts_as_citier looks a bit like this:
module Citier
def self.included(base)
# When a class includes a module the module’s self.included method will be invoked.
base.send :extend, ClassMethods
end
end
ActiveRecord::Base.send :include, Citier
Now.. Just by referencing Facility in my initial module it is going to the acts_as_citier gem and extending the ActiveRecord of my Site class. I want the acts_as_citier gem for my Facility but NOT for my Site.
Can anyone help stop this include trail bringing in this unwanted reference!?
EDIT
Seems like I can't reference the class Facility at all without it bringing in the ActiveRecord class additions that is defined in the Facility via it's reference to the gem act_as_citier
cities does this...
ActiveRecord::Base.send :include, Citier

class Facility < ActiveRecord::Base
#attr_accessible :name, :type, :facility_type_id, :accessibility_id, :tldc_id, :site_id, :tldc_approved
acts_as_citier if self.to_s == 'Facility' #Protects other classes from accidently getting the AR additions
Adding a condition to the include stops the acts_as_citier gem from extending any class that references 'Facility'.
I'm assuming the include on my Site class > runs through the module > which when it hits a reference to Facility class > runs through the Facility.rb > which runs through acts_as_citier and then hits the extend to active record line. It helped me remembering that every part of a .rb file is an executable.

Related

gem module method cant be included to ActiveRecord::Base

I have a module in my gem
module joinSelect
def self.with
puts 'with called'
end
ActiveRecord::Base.send :include, self
end
but I am unable to access method with in any of model classes
irb(main):015:0> User.with
NoMethodError: undefined method `with' for User (call 'User.connection' to establish a connection):Class
I have tried putting
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
include JoinSelect
#or
extend JoinSelect
end
``
doesen't work. How can I get "with" accessible on ApplicationRecord ?
Thanks in advance.
I'll recommend to include the module with your code only in the classes that will need that functionality. Including your code in ActiveRecord::Base is really not recommended, other gems you may use may conflict with it.
If you need your code to be available on all your ActiveRecord models, then define it in your ApplicationRecord. Since all your models will inherit from it, all will gain the functionality.
If you want to add a class method in your AR class, create a module with the function and extend it from your class:
module A
def foo
"Hi"
end
end
class User < ApplicationRecord
extend A
end
User.foo # => "Hi"
If you need to do more things, like declaring scopes, using ActiveRecord hooks, etc. then you'll need to use concerns, see here
define it without self in module
module JoinSelect
def with
puts 'with called'
end
end
and in ApplicationRecord use extend to include it as a class method
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
extend JoinSelect
end

Using ActiveRecord:Relation for specific classes, not all relations across ActiveRecord

I'm building a gem in which part of its purpose is to extend associations on a target Class. Although I can easily extend all associations by using something like :
ActiveRecord::Relation.send(:include, MyGem::ActiveRecord::RelationMethods)
This is too broad, and for a Rails App that may use this Gem, I don't want to extend associations for all Classes.
For better granularity, I want to provide the equivalent of :
class User < ActiveRecord::Base
has_many :messages, :extend => MyGem::ActiveRecord::RelationMethods
has_many :comments, :extend => MyGem::ActiveRecord::RelationMethods
end
By using
class User < ActiveRecord::Base
acts_as_my_fancy_gem
has_many :messages
has_many :comments
end
The problem I have is trying to conditionally extend associations within the Gem, when acts_as_my_fancy_gem is added to a class. This is the bare bones of it.
module MyGem
extend ActiveSupport::Concern
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def acts_as_my_fancy_gem
include MyGem::InstanceMethods
end
end
module InstanceMethods
...
end
end
I've looked into reflections, but at this point can find a clear path, and have simply taking stabs in the dark to experiment.
UPDATE:
Currently, I can achieve this with each association by providing a class method like
class User < ActiveRecord::Base
has_many :messages
has_many :comments
fancy_extend :messages
end
module MyGem
extend ActiveSupport::Concern
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def acts_as_my_fancy_gem
include MyGem::InstanceMethods
end
def fancy_extend *associations
class_eval do
associations.each do |association|
reflections[association].options[:extend] = MyGem::ActiveRecord::RelationMethods
end
end
end
end
module InstanceMethods
...
end
end
Adding this approach into the act_as_my_fancy method (which is where I would like to have it) gives me :
# NoMethodError: undefined method `options' for nil:NilClass
Is this rail4? I did not find the :extend option documented. It looks like rails 4 uses blocks to do that nowadays.
It could be as simple as this:
module Fancy
def has_many(name, scope = nil, options = {})
super(name, scope, options) do
def doit
"i did"
end
end
end
end
# in your model
extend Fancy
YourModel.your_relation.doit # => 'i did'

Creating a gem with associated Rails models

I would like to package a gem that includes ActiveRecord models that can be associated with models in the existing Rails application. I've been trying to follow the code for acts_as_taggable_on, but I'm running into some problems getting the associations to work.
My gem is called Kitchen. My model defined in the gem is Dish, and I want to add a polymorphic association (as Cook) to a model in the main application such as User.
In lib/kitchen.rb
require "active_record"
require "kitchen/dish.rb"
require "kitchen/cook.rb"
In lib/kitchen/dish.rb
module Kitchen
class Dish < ::ActiveRecord::Base
belongs_to :cook, :polymorphic => true
end
end
In lib/kitchen/cook.rb (lifting code from http://guides.rubyonrails.org/plugins.html#add-an-acts_as-method-to-active-record without much understanding)
module Kitchen
module Cook
extend ActiveSupport::Concern
included do
end
module ClassMethods
def acts_as_cook
class_eval do
has_many :dishes, :as => :cook
end
end
end
end
end
ActiveRecord::Base.send :include, Kitchen::Cook
Finally, I've migrated everything in my dummy app, and include the association in spec/dummy/app/models/user.rb
class User < ActiveRecord::Base
acts_as_cook
end
I'm getting an error any time I try to access user.dishes for a User instance:
NameError:
uninitialized constant User::Dish
Any idea what's missing?
Try this maybe:
has_many :dishes, :as => :cook, :class_name => 'Kitchen::Dish'

Rails extending ActiveRecord::Base

I've done some reading about how to extend ActiveRecord:Base class so my models would have some special methods. What is the easy way to extend it (step by step tutorial)?
There are several approaches :
Using ActiveSupport::Concern (Preferred)
Read the ActiveSupport::Concern documentation for more details.
Create a file called active_record_extension.rb in the lib directory.
require 'active_support/concern'
module ActiveRecordExtension
extend ActiveSupport::Concern
# add your instance methods here
def foo
"foo"
end
# add your static(class) methods here
class_methods do
#E.g: Order.top_ten
def top_ten
limit(10)
end
end
end
# include the extension
ActiveRecord::Base.send(:include, ActiveRecordExtension)
Create a file in the config/initializers directory called extensions.rb and add the following line to the file:
require "active_record_extension"
Inheritance (Preferred)
Refer to Toby's answer.
Monkey patching (Should be avoided)
Create a file in the config/initializers directory called active_record_monkey_patch.rb.
class ActiveRecord::Base
#instance method, E.g: Order.new.foo
def foo
"foo"
end
#class method, E.g: Order.top_ten
def self.top_ten
limit(10)
end
end
The famous quote about Regular expressions by Jamie Zawinski can be re-purposed to illustrate the problems associated with monkey-patching.
Some people, when confronted with a problem, think “I know, I'll use
monkey patching.” Now they have two problems.
Monkey patching is easy and quick. But, the time and effort saved is always extracted back
sometime in the future; with compound interest. These days I limit monkey patching to quickly prototype a solution in the rails console.
You can just extend the class and simply use inheritance.
class AbstractModel < ActiveRecord::Base
self.abstract_class = true
end
class Foo < AbstractModel
end
class Bar < AbstractModel
end
You can also use ActiveSupport::Concern and be more Rails core idiomatic like:
module MyExtension
extend ActiveSupport::Concern
def foo
end
module ClassMethods
def bar
end
end
end
ActiveRecord::Base.send(:include, MyExtension)
[Edit] following the comment from #daniel
Then all your models will have the method foo included as an instance method and the methods in ClassMethods included as class methods. E.g. on a FooBar < ActiveRecord::Base you will have: FooBar.bar and FooBar#foo
http://api.rubyonrails.org/classes/ActiveSupport/Concern.html
With Rails 4, the concept of using concerns to modularize and DRY up your models has been in highlights.
Concerns basically allow you to group similar code of a model or across multiple models in a single module and then use this module in the models. Here is a example:
Consider a Article model, a Event model and a Comment Model. A article or A event has many comments. A comment belongs to either article or event.
Traditionally, the models may look like this:
Comment Model:
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
Article Model:
class Article < ActiveRecord::Base
has_many :comments, as: :commentable
def find_first_comment
comments.first(created_at DESC)
end
def self.least_commented
#return the article with least number of comments
end
end
Event Model
class Event < ActiveRecord::Base
has_many :comments, as: :commentable
def find_first_comment
comments.first(created_at DESC)
end
def self.least_commented
#returns the event with least number of comments
end
end
As we can notice, there is a significant piece of code common to both Event and Article Model. Using concerns we can extract this common code in a separate module Commentable.
For this create a commentable.rb file in app/model/concerns.
module Commentable
extend ActiveSupport::Concern
included do
has_many :comments, as: :commentable
end
# for the given article/event returns the first comment
def find_first_comment
comments.first(created_at DESC)
end
module ClassMethods
def least_commented
#returns the article/event which has the least number of comments
end
end
end
And Now your models look like this :
Comment Model:
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
Article Model:
class Article < ActiveRecord::Base
include Commentable
end
Event Model
class Event < ActiveRecord::Base
include Commentable
end
One point I will like to highlight while using Concerns is that Concerns should be used for 'domain based' grouping rather than 'technical' grouping. For example, a domain grouping is like 'Commentable', 'Taggable' etc. A technical based grouping will be like 'FinderMethods', 'ValidationMethods'.
Here is a link to a post that I found very useful for understanding concerns in Models.
Hope the writeup helps :)
Step 1
module FooExtension
def foo
puts "bar :)"
end
end
ActiveRecord::Base.send :include, FooExtension
Step 2
# Require the above file in an initializer (in config/initializers)
require 'lib/foo_extension.rb'
Step 3
There is no step 3 :)
Rails 5 provides a built-in mechanism for extending ActiveRecord::Base.
This is achieved by providing additional layer:
# app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
# put your extensions here
end
and all models inherit from that one:
class Post < ApplicationRecord
end
See e.g. this blogpost.
With Rails 5, all models are inherited from ApplicationRecord & it gives nice way to include or extend other extension libraries.
# app/models/concerns/special_methods.rb
module SpecialMethods
extend ActiveSupport::Concern
scope :this_month, -> {
where("date_trunc('month',created_at) = date_trunc('month',now())")
}
def foo
# Code
end
end
Suppose the special methods module needs to be available across all models, include it in application_record.rb file. If we wants to apply this for a particular set of models, then include it in the respective model classes.
# app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
include SpecialMethods
end
# app/models/user.rb
class User < ApplicationRecord
include SpecialMethods
# Code
end
If you want to have the methods defined in the module as class methods, extend the module to ApplicationRecord.
# app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
extend SpecialMethods
end
Hope it help others !
Just to add to this topic, I spent a while working out how to test such extensions (I went down the ActiveSupport::Concern route.)
Here's how I set up a model for testing my extensions.
describe ModelExtensions do
describe :some_method do
it 'should return the value of foo' do
ActiveRecord::Migration.create_table :test_models do |t|
t.string :foo
end
test_model_class = Class.new(ActiveRecord::Base) do
def self.name
'TestModel'
end
attr_accessible :foo
end
model = test_model_class.new(:foo => 'bar')
model.some_method.should == 'bar'
end
end
end
I have
ActiveRecord::Base.extend Foo::Bar
in an initializer
For a module like below
module Foo
module Bar
end
end

Where to put common code found in multiple models?

I have two models that contain the same method:
def foo
# do something
end
Where should I put this?
I know common code goes in the lib directory in a Rails app.
But if I put it in a new class in lib called 'Foo', and I need to add its functionality to both of my ActiveRecord models, do I do that like this:
class A < ActiveRecord::Base
includes Foo
class B < ActiveRecord::Base
includes Foo
and then both A and B will contain the foo method just as if I had defined it in each?
Create a module, which you can put in the lib directory:
module Foo
def foo
# do something
end
end
You can then include the module in each of your model classes:
class A < ActiveRecord::Base
include Foo
end
class B < ActiveRecord::Base
include Foo
end
The A and B models will now have a foo method defined.
If you follow Rails naming conventions with the name of the module and the name of the file (e.g. Foo in foo.rb and FooBar in foo_bar.rb), then Rails will automatically load the file for you. Otherwise, you will need to use require_dependency 'file_name' to load your lib file.
You really have two choices:
Use a module for common logic and include it in A & B
Use a common class C that extends ActiveRecord and have A & B extend C.
Use #1 if the shared functionality is not core to each class, but applicable to each class. For example:
(app/lib/serializable.rb)
module Serializable
def serialize
# do something to serialize this object
end
end
Use #2 if the shared functionality is common to each class and A & B share a natural relationship:
(app/models/letter.rb)
class Letter < ActiveRecord::Base
def cyrilic_equivilent
# return somethign similar
end
end
class A < Letter
end
class B < Letter
end
Here's how I did it... First create the mixin:
module Slugged
extend ActiveSupport::Concern
included do
has_many :slugs, :as => :target
has_one :slug, :as => :target, :order => :created_at
end
end
Then mix it into every model that needs it:
class Sector < ActiveRecord::Base
include Slugged
validates_uniqueness_of :name
etc
end
It's almost pretty!
To complete the example, though it's irrelevant to the question, here's my slug model:
class Slug < ActiveRecord::Base
belongs_to :target, :polymorphic => true
end
One option is to put them in a new directory, for example app/models/modules/. Then, you can add this to config/environment.rb:
Dir["#{RAILS_ROOT}/app/models/modules/*.rb"].each do |filename|
require filename
end
This will require every file in in that directory, so if you put a file like the following in your modules directory:
module SharedMethods
def foo
#...
end
end
Then you can just use it in your models because it will be automatically loaded:
class User < ActiveRecord::Base
include SharedMethods
end
This approach is more organized than putting these mixins in the lib directory because they stay near the classes that use them.
If you need ActiveRecord::Base code as a part of your common functionalities, using an abstract class could be useful too. Something like:
class Foo < ActiveRecord::Base
self.abstract_class = true
#Here ActiveRecord specific code, for example establish_connection to a different DB.
end
class A < Foo; end
class B < Foo; end
As simple as that. Also, if the code is not ActiveRecord related, please find ActiveSupport::Concerns as a better approach.
As others have mentioned include Foo is the way to do things... However it doesn't seem to get you the functionality you want with a basic module. The following is the form a lot of Rails plugins take to add class methods and new callbacks in addition to new instance methods.
module Foo #:nodoc:
def self.included(base) # :nodoc:
base.extend ClassMethods
end
module ClassMethods
include Foo::InstanceMethods
before_create :before_method
end
module InstanceMethods
def foo
...
end
def before_method
...
end
end
end

Resources