Modularizing class-level method calls by evaluating them in `included` methods - ruby-on-rails

I'm working with a Rails project that uses the flip gem for feature flags. We have a Feature class in which you can declare the various feature flags you want to use,
# app/models/feature.rb
class Feature < ActiveRecord::Base
extend Flip::Declarable
strategy Flip::DeclarationStrategy
feature :ivans_feature_A
feature :ivans_feature_B
feature :ivans_feature_C
feature :kramers_feature_X
feature :kramers_feature_X
end
As the project grows, so does the number of feature-flags we've got declared in this file. A coworker suggested we break related feature-declarations into separate modules to organize things.
I've found a way to do this, but it's not a pattern I've seen used before so I wonder if there's a more standard way. I'm defining namespaced modules for each bunch of features I want to group together:
app/models/features/ivans_features.rb
module Features::IvansFeatures
def self.included(base)
base.feature :ivans_feature_A
base.feature :ivans_feature_B
base.feature :ivans_feature_C
end
end
app/models/features/kramers_features.rb
module Features::KramersFeatures
def self.included(base)
base.feature :kramers_feature_X
base.feature :kramers_feature_Y
end
end
...and including them in the feature model:
# app/models/feature.rb
class Feature < ActiveRecord::Base
extend Flip::Declarable
strategy Flip::DeclarationStrategy
include Features::IvansFeatures
include Features::KramersFeatures
end
Is it strange to mix a module into a class for the sole purpose of usingthe included callback to run some method calls on the class?

In your Feature class you can extend ActiveSupport::Concern and then do something like
included do
feature :kramers_feature_X
end

Related

Dynamic concerns with inheritance not loading twice, but only once

We are loading code dynamically with concerns, based on some environment variables, which works pretty nice.
Something like this:
# User class
class User
include DynamicConcern
end
module DynamicConcern
extend ActiveSupport::Concern
included do
if "Custom::#{ENV["CUSTOMER_NAME"].camelize}::#{self.name}Concern".safe_constantize
include "Custom::#{ENV["CUSTOMER_NAME"].camelize}::#{self.name}Concern".constantize
end
end
end
# custom code
module Custom::Custom123::UserConcern
extend ActiveSupport::Concern
included do
...
end
end
We are using this since years and it worked absolutely fine in models. Some days ago we tried to use the same approach with Controllers, but realized that this approach doesn'
t work fine with inheritance, where the parent class inherits the concern as well as the inherited class:
class ApplicationController < ActionController::Base
# this gets loaded and includes the right dynamic module
include DynamicConcern
end
class ShopController < ApplicationController
# this is NOT getting loaded again and skipped,
# since it has been loaded already in the parent controller
include DynamicConcern
end
Is there a way to tell rails that it should include/evaluade the concern a second time, since the second time it would have another class name which would include another module?
I'm not looking for other solutions, since a lot of our code is based on this approach and I think it's possible to solve this without rewriting everything.
Thanks!
You are only trying to dynamically include modules based on the class name.
It's not necessary to make a concern but it can be a normal class, and the include action can be a normal method. Every time you want to call it, just call it like any other method.
Because you have already written your code with ActiveSupport::Concern in an include fashion. I guess the following refactor may work even though I cannot guarantee it. The idea is simple:
Just make it a normal method with the target class as the parameter. You can include it (it automatically calls dynamic_include in included hook).
If the module is already included in the ancestor hierarchy chain, just invoke the dynamic_include will immediately call the method and do the dynamic includes.
Please give it a try and let me know if it works for your scenarios.
module DynamicConcern
extend ActiveSupport::Concern
included do
def self.dynamic_include(klass)
if "Custom::#{ENV["CUSTOMER_NAME"].camelize}::#{klass.name}Concern".safe_constantize
klass.include "Custom::#{ENV["CUSTOMER_NAME"].camelize}::#{klass.name}Concern".constantize
end
end
dynamic_include(self)
end
end
class ApplicationController < ActionController::Base
# this gets loaded and includes the right dynamic module
include DynamicConcern
end
class ShopController < ApplicationController
# this is NOT getting loaded again and skipped,
# since it has been loaded already in the parent controller
dynamic_include(self)
end
Actually it's a feature of Rails that the same module doesn't get loaded multiple times.
We started to use the normal ruby module inclution hooks and it worked fine!
module CustomConcern
def self.included(base)
custom_class_lookup_paths = [
"#{HOSTNAME.camelize}::Models::#{base.name}PrependConcern",
"#{HOSTNAME.camelize}::Controllers::#{base.name}PrependConcern"
].map{|class_string| class_string.safe_constantize }.compact
custom_class_lookup_paths.each do |class_string|
base.send :include, class_string
end
end

Where to store 'concerns' in a Ruby on Rails project? (Rails 5.2+)

I am fairly new to RoR. I have spent the afternoon reading about modules (used as concerns). I have yet to find a good article which describes the file path that using include or extend methods looks up (if include and extend are methods?).
The most specific example I have found was here: Ruby On Rails - Using concerns in controllers. This makes me feel that if I wanted to include the 'Bar' module in my Foo model I would create a concerns/ directory in my models/ directory, and create a 'Bar' module file in this folder.
# in models/concerns/bar.rb
modlue Bar
# do I need this???
extend ActiveSupport::Concern
def speak_bar
puts "model module bar!"
end
end
# in models/foo.rb
class Foo < ApplicationRecord
include Bar
end
# I could then perform:
Foo.new.speak_bar
=> "model module bar!"
And if I wanted to include a Bar module in my Foo controller I would do:
# in controllers/concerns/bar.rb
modlue Bar
# Again, do I need this???
extend ActiveSupport::Concern
def speak_bar
return "controller module bar!"
end
end
# in controllers/foo.rb
class FoosController < ApplicationController
include Bar
def make_bar
#bar = speak_bar
end
end
# I could then use #bar in my views (anywhere else?) as <%= #bar %> and get it to output
=> "controller module bar!"
Summary of questions:
Is this understanding set out above correct in terms of the file paths?
And do I need to use the extend ActiveSupport::Concern line in order to use this path system?
Are include and extend methods?
Thank you for your help.
You should always extend your concerns module with the supplied concerns base from Rails.
Pathing is usually app/models/concerns/file.rb for model concerns and app/controllers/file.rb for controllers and so on.
If you specifically have logic that crosses the controller and models separation, consider placing that in lib, and adding lib to your autoload path.
include and extend are methods. Most things (almost all) are objects in ruby. So almost all operations are methods on objects.
the file path that using include or extend Rails does some magic when starting to autoload a lot of things so you don't have to worry later when you call "Bar". This talk is really helpfull to understand WHY you can just do include Bar inside a rails model without much thinking https://www.youtube.com/watch?v=I0a5zv7uBHw
Usually, you want model related concerns inside /app/models/concerns and controller related concerns inside /app/controllers/concerns, but that's just for organization purposes, rails will autoload them even if you use /app/whatever/concerns, so be carefull about name collisions.
You DO need to extend ActiveSupport::Concern if you want to use the syntax sugar that Concerns provide, but at the end they are just modules that can be included. https://api.rubyonrails.org/classes/ActiveSupport/Concern.html check this examples, concerns are just a way to write modules to share behaviour with a more friendly syntax for common rails patterns.
extend is a method of Object https://docs.ruby-lang.org/en/2.6.0/Object.html#method-i-extend
include is a method of Module https://docs.ruby-lang.org/en/2.6.0/Module.html#method-i-include (and Module inherits extend from Object)
concerns are auto-loaded by rails by default starting from rails v4+. You can read the article written by DHH to get a fair idea of what concern does and what does it try to solve.
However, it gets pretty complicated in determining which scope you are in and what self is in the method. Check out this video by Ryan Bates regarding the problems with concerns.
To solve some parts of the problem, I generally nest the concern inside a folder and refer it by giving a class. For example
# app/models/concerns/user/authentication.rb
class User
module Authentication
extend ActiveSupport::Concern
# stuff
end
end
and include in the model like
# app/models/user.rb
include Authentication
In my opinion, the separation of concerns helps in isolating your methods. For example, you can create a Filterable concern in a similar way, and isolate it from your other models.

Rails namespacing concerns based on model name

I am looking to separate concerns for some subset of function specific to a model.
I have referenced here and followed this pattern
module ModelName::ConcernName
extend ActiveSupport::Concern
included do
# class macros
end
# instance methods
def some_instance_method
end
module ClassMethods
# class methods here, self included
end
end
However, when I try to start the server it would result in the following error
Circular dependency detected while autoloading constant ModelName::ConcernName
I am wondering what is the best way to do concerns for some subset functions of a model.
Edit
Providing the model code:
path: app/models/rent.rb
Now I have a lot of checking logic in my model
class Rent < ActiveRecord::Base
def pricing_ready?
# check if pricing is ready
end
def photos_ready?
# check if photo is ready
end
def availability_ready?
# check if availability setting is ready
end
def features_ready?
# check if features are set
end
end
I want to separate it in concern
class Rent < ActiveRecord::Base
include Rent::Readiness
end
And organise the concern by namespace
path: app/models/concerns/rent/readiness.rb
module Rent::Readiness
extend ActiveSupport::Concern
included do
# class macros
end
# instance methods
def pricing_ready?
# check if pricing is ready
end
...
module ClassMethods
# class methods here, self included
end
end
Now I got it working if I just do class RentReadiness with the path in app/models/concerns/rent_readiness.rb
You can scope it to Rents and place to concerns/rents/readiness.rb:
module Rents
module Readiness
extend ActiveSupport::Concern
included do
# class macros
end
end
end
And in model:
class Rent < ActiveRecord::Base
include Rents::Readiness
end
You can make it work by just moving the folder with model-specific concerns from concerns to models. So, you would have:
models/
rent.rb
rent/
readiness.rb
I like this convention of using the model as the namespace for its concerns because it lets you remove some redundancy from code:
Since you are defining the concern within the model class, in the model you can write include Readiness instead of include Rent::Readiness
When defining the concern, you can use module Rent::Readiness instead of
class Rent < ApplicationRecord
module Readiness
...
Which would be another way of fixing the circular dependency problem you mentioned in your question.
Rails uses activesupport to load classes and modules as they are defined by inferring the file path based on the class or module name, this is done as the Ruby parser loads your files and come across a new constant that has not been loaded yet. In your case, the Rent model is parsed up to the Rent::Readlines reference, at which point activesupport goes off to look for the rent/readlines.rb code file that matches the name. This file is then then parsed by ruby, but on the first line, The still unloaded Rent class is referenced, which triggers activesupport to go off and look for the code file that matches the name.

How to refactor "shared" methods?

I am using Ruby on Rails 3.2.2 and I would like to "extract" some methods from my models / classes. That is, in more than one class / model I have some methods (note: methods are related to user authorizations and are named the "CRUD way") that are and work practically the same; so I thought that a DRY approach is to put those methods in a "shared" module or something like that.
What is a common and right way to accomplish that? For example, where (in which directories and files) should I put the "shared" code? how can I include mentioned methods in my classes / models? what do you advice about?
Note: I am looking for a "Ruby on Rails Way to make things".
One popular approach is to use ActiveSupport concerns. You would then place the common logic typically under app/concerns/ or app/models/concerns/ directory (based on your preference). An illustrative example:
# app/concerns/mooable.rb
module Mooable
extend ActiveSupport::Concern
included do
before_create :say_moo
self.mooables
where(can_moo: true)
end
end
private
def say_moo
puts "Moo!"
end
end
And in the model:
# app/models/cow.rb
class Cow < ActiveRecord::Base
include Mooable
end
In order to make it work this way you have to add the following line to config/application.rb
config.autoload_paths += %W(#{config.root}/app/concerns)
More information:
http://chris-schmitz.com/extending-activemodel-via-activesupportconcern/
http://blog.waxman.me/extending-your-models-in-rails-3
http://api.rubyonrails.org/classes/ActiveSupport/Concern.html
My answer has nothing to do with RoR directly but more with Ruby.
Shraing common code may be done in various ways in Ruby. In my opinion the most obvious way is to create Ruby Modules that contain the code and then include them inside your class/model. Those shared modules are frequently under the lib directory of your app root. For example:
# lib/authorizable.rb
module Authorizable
def method1
#some logic here
end
def method2
#some more logic here
end
end
# app/models/user.rb
class User < ActiveRecord::Base
include Authorizable
end
The User class may now invoke method1 and method2 which belong to the Authorizable module. You can include this module in any other Ruby class you'd like, this way you DRY your code.

how to define/attach rails validations in multiple generations of modules

I've found a way to make this work, but am curious about a better way / the Rails 3 way. (I'm using 2.3.5 still, but hope to migrate around New Year's.)
The situation: I've got two layers of module inheritance, the second layer gets mixed into a Rails model. Both modules define validation methods and I'd like both of them to attach the validations to the base class, but because of the two levels of inheritance, the following doesn't work:
def self.included(base)
base.validate :yadda_yadda
end
When that module is included by another module, the interpreter grinds to a screeching halt because Modules don't know about ActiveRecord::Validations. Including the validations module begs the question of "where is save?" thanks to alias_method.
The following works, as long as you remember to call super whenever you override validate(). I don't trust myself or future maintainers to remember that, so I'd like to use the validate :yadda_yadda idiom instead, if possible.
module Grandpa
def validate
must_be_ok
end
def must_be_ok
errors.add_to_base("#{self} wasn't ok")
end
end
module Dad
include Grandpa
def validate
super
must_be_ok_too
end
def must_be_ok_too
errors.add_to_base("#{self} wasn't ok either")
end
end
class Kid < ActiveRecord::Base
include Dad
validate :must_be_ok_three
def must_be_ok_three
errors.add_to_base("#{self} wasn't ok furthermore")
end
end
Suggestions? Tips for Rails 3 approach? I don't think the validations API has changed that much.
I solved it (when I ran into the same problem, but with something other than validation).
Short answer: you can call send(:included, base) on the module you want to bring in. Within the higher-up included() definition, you need to check whether the base is a Class or a Module.
Why would you ever want to do this? Well, I've got some modules that extract some common functionality out of my models. For instance, the module HasAllocable sets up a polymorphic belongs_to relationship, and a getter/setter pair for a virtual attribute. Now I have another module that needs to pull in HasAllocable, to spare the base classes from having to remember it.
I'd be interested to know whether this smells funny to anyone. I haven't seen anything like it on the web, so I wonder if multiple layers of model inheritance is more of an antipattern.
module Grandpa
def self.included(base)
if base.kind_of?(Class)
base.validate :must_be_ok
end
end
end
module Dad
include Grandpa
def self.included(base)
if base.kind_of?(Class)
# you can do this
#base.send(:include, Grandpa)
# you can also do this
Grandpa.send(:included, base)
# this does not invoke Grandpa.included(Kid)
#super(base)
base.validate :must_be_ok_too
end
end
end
class Kid < ActiveRecord::Base
include Dad
validate :must_be_ok_three
end

Resources