How to use the Attribute API inside a concern in a Rails? - ruby-on-rails

I have a simple generic model rails that looks like this:
class Thing < ApplicationRecord
attribute :foo, :integer
include AConcern
end
And it include a basic concern that looks like this…
module AConcern
extend ActiveSupport::Concern
end
The model also has an attribute called :foo using the attribute api from below:
https://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html
The attribute relates to the the concern, so every time I want to use the concern, in each model I have to define the attribute and then include the concern.
If I put the attribute declration inside the concern like this:
module AConcern
extend ActiveSupport::Concern
attribute :foo, :integer
end
I get the following error:
undefined method `attribute' for AConcern:Module
How do I use the attribute definition in the concern so I don’t have to declare it in every model before including the concern? Thanks

You can use ActiveSupport::Concern included hook to handle this e.g.
module AConcern
extend ActiveSupport::Concern
included do
attribute :foo, :integer
end
end
Then
class Thing < ApplicationRecord
include AConcern
end
The problem you are experiencing right now is that attribute is being called in the context of your Module but that module does not have access to that method (hence NoMethodError).
The included hook is run when you call include and the hook is run in the context of the including Object ( Thing in this case). Thing does have the attribute method and thus everything works as expected.
included block from ActiveSupport::Concern is essentially the same as (in pure ruby)
module AConcern
def self.included(base)
base.class_eval { attribute :foo, :integer }
end
end

Related

Adding uniqueness validation for dynamic attributes in rails

We have a multi-tenant application where validation differs for each account. We could easily achieve this for presence validation like the below,
module CommonValidator
def add_custom_validation
required_fields = get_required_fields
return if required_fields.blank?
validates_presence_of required_fields.map(&:to_sym)
end
end
class ApplicationRecord < ActiveRecord::Base
include Discard::Model
include CommonValidator
end
Then we have to add uniqueness validation based on account, so tried like the same. but getting undefined method error. Is there any way that I could get this work?
module CommonValidator
def add_custom_validation
unique_fields = ['first_name']
validates_uniqueness_of unique_fields.map(&:to_sym) if unique_fields.present?
end
end
validates_uniqueness_of is actually a class method (defined in ActiveRecord::Validations::ClassMethods), hence you are not able to call it from the context of the object.
Whereas validates_presence_of is both a helper method, and a class method (defined in ActiveModel::Validations::HelperMethods and ActiveRecord::Validations::ClassMethods).
If you want to use the uniqueness validator, you can define the add_custom_validation as a class method as well and then you should be able to use it. Something like,
require 'active_support/concern'
module CommonValidator
extend ActiveSupport::Concern
included do
add_custom_validation
end
class_methods do
def add_custom_validation
required_fields = get_required_fields # This will also need to be a class method now
return if required_fields.blank?
validates_uniqueness_of required_fields.map(&:to_sym)
end
end
end

trying to get name of enclosing class in a Rails concern

First time using concerns and just looking for some advice.
I have a Rails model called location.rb and would like to include an AlbumDefineConcern and then query which model class we are currently in (in this class Location).
I have:
class Location < ActiveRecord::Base
include AlbumDefineConcern
...
and
module AlbumDefineConcern
extend ActiveSupport::Concern
albums={}
albums_locations = ["LocationHomeFeed","LocationProfile","LocationMobileMain"]
albums[:locations]=albums_locations
# I'd like it to output location or Location
puts "here is class_name #{self.name}"
How would I get "location" as the class name?
# puts "here is class_name #{self.parent.name}" => Object
module AlbumDefineConcern
extend ActiveSupport::Concern
included do
puts self
end
end

Adding scope to ActiveRecord causes hierarchy error

I've just converted all of my Rails models to use uuid as a primary key replacement, but this breaks the #first and #last methods so I'm trying to add a default scope that sorts by created_at instead of id.
My concern looks like this:
# config/initializers/uuid_support.rb
module
extend ActiveSupport::Concern
included do
default_scope -> { order 'created_at ASC' }
end
end
ActiveRecord::Base.send :include, UuidSupport
Once this has been added, the following error gets thrown when performing a fetch on any model: ActiveRecord::ActiveRecordError: ActiveRecord::Base doesn't belong in a hierarchy descending from ActiveRecord.
Looks like you're trying to create a concern and have your models include it. For that, I recommend a different approach and not do it through an initializer, but rather as an actual concern, the way Rails intended it.
Get rid of your initializer, and put the following code in app/models/concerns/module_name.rb:
module ModuleName # replace with desired name
extend ActiveSupport::Concern
included do
default_scope -> { order 'created_at ASC' }
end
end
If <= Rails 3, add this to application.rb to load the concerns:
config.autoload_paths += %W(
#{config.root}/app/models/concerns
)
Include your concern in your models by doing
include ModuleName
at the beginning of your models.
If the reason you did this with an initializer is because you want every model to include this behavior, now is the time to write an initializer.
Either as monkey patch:
# config/initializers/name.rb
class ActiveRecord::Base
include ModuleName
end
or like you did:
# config/initializers/name.rb
ActiveRecord::Base.send :include, ModuleName

How to use concerns in Rails 4

The default Rails 4 project generator now creates the directory "concerns" under controllers and models. I have found some explanations about how to use routing concerns, but nothing about controllers or models.
I am pretty sure it has to do with the current "DCI trend" in the community and would like to give it a try.
The question is, how am I supposed to use this feature, is there a convention on how to define the naming / class hierarchy in order to make it work? How can I include a concern in a model or controller?
So I found it out by myself. It is actually a pretty simple but powerful concept. It has to do with code reuse as in the example below. Basically, the idea is to extract common and / or context specific chunks of code in order to clean up the models and avoid them getting too fat and messy.
As an example, I'll put one well known pattern, the taggable pattern:
# app/models/product.rb
class Product
include Taggable
...
end
# app/models/concerns/taggable.rb
# notice that the file name has to match the module name
# (applying Rails conventions for autoloading)
module Taggable
extend ActiveSupport::Concern
included do
has_many :taggings, as: :taggable
has_many :tags, through: :taggings
class_attribute :tag_limit
end
def tags_string
tags.map(&:name).join(', ')
end
def tags_string=(tag_string)
tag_names = tag_string.to_s.split(', ')
tag_names.each do |tag_name|
tags.build(name: tag_name)
end
end
# methods defined here are going to extend the class, not the instance of it
module ClassMethods
def tag_limit(value)
self.tag_limit_value = value
end
end
end
So following the Product sample, you can add Taggable to any class you desire and share its functionality.
This is pretty well explained by DHH:
In Rails 4, we’re going to invite programmers to use concerns with the
default app/models/concerns and app/controllers/concerns directories
that are automatically part of the load path. Together with the
ActiveSupport::Concern wrapper, it’s just enough support to make this
light-weight factoring mechanism shine.
I have been reading about using model concerns to skin-nize fat models as well as DRY up your model codes. Here is an explanation with examples:
1) DRYing up model codes
Consider a Article model, a Event model and a Comment model. An article or an 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. Using concerns we can extract this common code in a separate module Commentable.
For this create a commentable.rb file in app/models/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
2) Skin-nizing Fat Models.
Consider a Event model. A event has many attenders and comments.
Typically, the event model might look like this
class Event < ActiveRecord::Base
has_many :comments
has_many :attenders
def find_first_comment
# for the given article/event returns the first comment
end
def find_comments_with_word(word)
# for the given event returns an array of comments which contain the given word
end
def self.least_commented
# finds the event which has the least number of comments
end
def self.most_attended
# returns the event with most number of attendes
end
def has_attendee(attendee_id)
# returns true if the event has the mentioned attendee
end
end
Models with many associations and otherwise have tendency to accumulate more and more code and become unmanageable. Concerns provide a way to skin-nize fat modules making them more modularized and easy to understand.
The above model can be refactored using concerns as below:
Create a attendable.rb and commentable.rb file in app/models/concerns/event folder
attendable.rb
module Attendable
extend ActiveSupport::Concern
included do
has_many :attenders
end
def has_attender(attender_id)
# returns true if the event has the mentioned attendee
end
module ClassMethods
def most_attended
# returns the event with most number of attendes
end
end
end
commentable.rb
module Commentable
extend ActiveSupport::Concern
included do
has_many :comments
end
def find_first_comment
# for the given article/event returns the first comment
end
def find_comments_with_word(word)
# for the given event returns an array of comments which contain the given word
end
module ClassMethods
def least_commented
# finds the event which has the least number of comments
end
end
end
And now using Concerns, your Event model reduces to
class Event < ActiveRecord::Base
include Commentable
include Attendable
end
* While using concerns its advisable to go for 'domain' based grouping rather than 'technical' grouping. Domain Based grouping is like 'Commentable', 'Photoable', 'Attendable'. Technical grouping will mean 'ValidationMethods', 'FinderMethods' etc
It's worth to mention that using concerns is considered bad idea by many.
like this guy
and this one
Some reasons:
There is some dark magic happening behind the scenes - Concern is patching include method, there is a whole dependency handling system - way too much complexity for something that's trivial good old Ruby mixin pattern.
Your classes are no less dry. If you stuff 50 public methods in various modules and include them, your class still has 50 public methods, it's just that you hide that code smell, sort of put your garbage in the drawers.
Codebase is actually harder to navigate with all those concerns around.
Are you sure all members of your team have same understanding what should really substitute concern?
Concerns are easy way to shoot yourself in the leg, be careful with them.
This post helped me understand concerns.
# app/models/trader.rb
class Trader
include Shared::Schedule
end
# app/models/concerns/shared/schedule.rb
module Shared::Schedule
extend ActiveSupport::Concern
...
end
I felt most of the examples here demonstrated the power of module rather than how ActiveSupport::Concern adds value to module.
Example 1: More readable modules.
So without concerns this how a typical module will be.
module M
def self.included(base)
base.extend ClassMethods
base.class_eval do
scope :disabled, -> { where(disabled: true) }
end
end
def instance_method
...
end
module ClassMethods
...
end
end
After refactoring with ActiveSupport::Concern.
require 'active_support/concern'
module M
extend ActiveSupport::Concern
included do
scope :disabled, -> { where(disabled: true) }
end
class_methods do
...
end
def instance_method
...
end
end
You see instance methods, class methods and included block are less messy. Concerns will inject them appropriately for you. That's one advantage of using ActiveSupport::Concern.
Example 2: Handle module dependencies gracefully.
module Foo
def self.included(base)
base.class_eval do
def self.method_injected_by_foo_to_host_klass
...
end
end
end
end
module Bar
def self.included(base)
base.method_injected_by_foo_to_host_klass
end
end
class Host
include Foo # We need to include this dependency for Bar
include Bar # Bar is the module that Host really needs
end
In this example Bar is the module that Host really needs. But since Bar has dependency with Foo the Host class have to include Foo (but wait why does Host want to know about Foo? Can it be avoided?).
So Bar adds dependency everywhere it goes. And order of inclusion also matters here. This adds lot of complexity/dependency to huge code base.
After refactoring with ActiveSupport::Concern
require 'active_support/concern'
module Foo
extend ActiveSupport::Concern
included do
def self.method_injected_by_foo_to_host_klass
...
end
end
end
module Bar
extend ActiveSupport::Concern
include Foo
included do
self.method_injected_by_foo_to_host_klass
end
end
class Host
include Bar # It works, now Bar takes care of its dependencies
end
Now it looks simple.
If you are thinking why can't we add Foo dependency in Bar module itself? That won't work since method_injected_by_foo_to_host_klass have to be injected in a class that's including Bar not on Bar module itself.
Source: Rails ActiveSupport::Concern
In concerns make file filename.rb
For example I want in my application where attribute create_by exist update there value by 1, and 0 for updated_by
module TestConcern
extend ActiveSupport::Concern
def checkattributes
if self.has_attribute?(:created_by)
self.update_attributes(created_by: 1)
end
if self.has_attribute?(:updated_by)
self.update_attributes(updated_by: 0)
end
end
end
If you want to pass arguments in action
included do
before_action only: [:create] do
blaablaa(options)
end
end
after that include in your model like this:
class Role < ActiveRecord::Base
include TestConcern
end

Override model's attribute accessor in a mixin/module

I have a model which includes a module. I'd like to override the model's accessor methods within the module.
For example:
class Blah < ActiveRecord::Base
include GnarlyFeatures
# database field: name
end
module GnarlyFeatures
def name=(value)
write_attribute :name, "Your New Name"
end
end
This obviously doesn't work. Any ideas for accomplishing this?
Your code looks correct. We are using this exact pattern without any trouble.
If I remember right, Rails uses #method_missing for attribute setters, so your module will take precedence, blocking ActiveRecord's setter.
If you are using ActiveSupport::Concern (see this blog post, then your instance methods need to go into a special module:
class Blah < ActiveRecord::Base
include GnarlyFeatures
# database field: name
end
module GnarlyFeatures
extend ActiveSupport::Concern
included do
def name=(value)
write_attribute :name, value
end
end
end

Resources